【Linux线程同步专题】四、信号量

简介: 【Linux线程同步专题】四、信号量

1. 什么是信号量

信号量相当于进化版的互斥锁。由于互斥锁的粒度比较大,如果我们希望在多个线程间对某一对象的部分数据进行共享,使用互斥锁是没有办法实现的,只能将整个数据对象锁住。这样虽然达到了多线程操作共享数据时保证数据正确性的目的,却无形中导致线程的并发性下降,线程从并行执行变成了串行执行,与直接使用单进程无异。信号量是相对折衷的一种处理方式,既能保证同步,数据不混乱,又能提高线程并发。

可以这么理解,比如说现在有一个资源可以允许三个线程同时访问,如果用互斥量的话,当第一个线程获取互斥锁的时候,后面的线程都会阻塞,这就无法实现三个线程同时访问资源了,会大大降低资源的利用效率。如果使用信号量,那个给信号量一个初值,每有一个线程访问到资源,信号量就减一,当减到0的时候,说明已经满足最多同时访问的线程数量了,后面的线程就不能再访问资源了,会阻塞。

2. 信号量相关API

2.1 初始化一个信号量

  • 头文件及函数原型
#include <semaphore.h>
int sem_init(sem_t *sem, int pshared, unsigned int value);
Link with -lrt or -pthread.
  • 函数描述
    sem_init() initializes the unnamed semaphore at the address pointed to by sem. The value argument specifies the initial value for the semaphore.
  • 函数参数
  • sem:传输参数,代表信号量,不能小于0。sem_t信号量数据类型,是一个结构体,可以简单理解为类似于文件描述符的东西。sem_t数据类型的实现是对用户隐藏的,所以在后面的++和–操作都是只能通过函数sem_wait和sem_post来实现。信号量的初值决定了占用信号量的线程的个数。
  • pshared:
  • 0:用于线程间
  • 非0:用于进程间
  • value:指定信号量初值
  • 函数返回值
    sem_init() returns 0 on success; on error, -1 is returned, and errno is set to indicate the error.

2.2 销毁一个信号量

  • 头文件及函数原型
#include <semaphore.h>
int sem_destroy(sem_t *sem);
Link with -lrt or -pthread.
  • 函数描述
    sem_destroy() destroys the unnamed semaphore at the address pointed to by sem.
  • 函数参数
  • sem
  • 函数返回值
    sem_destroy() returns 0 on success; on error, -1 is returned, and errno is set to indicate the error.

2.3 申请一个信号量(申请成功value–)

  • 头文件及函数原型
#include <semaphore.h>
/*--操作*/
int sem_wait(sem_t *sem);
int sem_trywait(sem_t *sem);
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
Link with -lrt or -pthread.
  • 函数描述
  • sem_wait() decrements (locks) the semaphore pointed to by sem. 信号量大于0,则信号量–,信号量等于0,则线程阻塞。
  • sem_trywait() is the same as sem_wait(), except that if the decrement can not be immediately performed, then call returns an error (errno set to EAGAIN) instead of blocking.
  • sem_timedwait() is the same as sem_wait(), except that abs_timeout specifies a limit on the amount of time that the call should block if the decrement cannot be immediately performed.
  • 函数参数
  • sem
  • 函数返回值
    All of these functions return 0 on success; on error, the value of the semaphore is left unchanged, -1 is returned, and errno is set to indicate the error.

2.4 释放信号量(value++)

  • 头文件及函数原型
#include <semaphore.h>
/*++操作*/
int sem_post(sem_t *sem);
Link with -lrt or -pthread.
  • 函数描述
    sem_post() increments (unlocks) the semaphore pointed to by sem. 信号量++,同时唤醒阻塞在信号量上的线程。
  • 函数参数
  • sem
  • 函数返回值
    sem_post() returns 0 on success; on error, the value of the semaphore is left unchanged, -1 is returned, and errno is set to indicate the error.

3. 信号量实现生产者消费者模型

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define MAX 6
sem_t blank, ful;
int vector[MAX];
int gdata = 100;
void* producer_th(void* arg)
{
    int i = 0;
    while(1)
    {
        sem_wait(&blank);
        printf("thread: %s, tid: %lu, data: %d\n", __FUNCTION__,\
               pthread_self(), gdata);
        vector[(i++)%MAX] = gdata++;
        sem_post(&ful);
        sleep(rand()%3);
    }
    return NULL;
}
void* consumer_th(void* arg)
{
    int i = 0;
    int num = 0;
    while(1)
    {
        sem_wait(&ful);
        num = vector[(i++) % MAX];
        printf("thread: %s, tid: %lu, data: %d\n", __FUNCTION__,\
               pthread_self(), num);
        sem_post(&blank);
        sleep(rand()%3);
    }
    return NULL;
}
int main(int argc, char* argv[])
{
    sem_init(&blank, 0, MAX); /*生产者*/
    sem_init(&ful, 0, 0); /*消费者*/
    pthread_t t1, t2;
    pthread_create(&t1, NULL, producer_th, NULL);
    pthread_create(&t2, NULL, consumer_th, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    sem_destroy(&blank);
    sem_destroy(&ful);
    return 0;
}


相关文章
|
14天前
|
算法 Unix Linux
linux线程调度策略
linux线程调度策略
26 0
|
15天前
|
缓存 Linux C语言
Linux线程是如何创建的
【8月更文挑战第5天】线程不是一个完全由内核实现的机制,它是由内核态和用户态合作完成的。
|
5天前
|
缓存 Linux C语言
Linux中线程是如何创建的
【8月更文挑战第15天】线程并非纯内核机制,由内核态与用户态共同实现。
|
12天前
|
关系型数据库 Linux 数据库
linux设置信号量系统参数
linux设置信号量系统参数
|
1月前
|
Linux
【Linux】生产者消费者模型——环形队列RingQueue(信号量)
【Linux】生产者消费者模型——环形队列RingQueue(信号量)
22 0
|
1月前
|
安全 算法 Linux
【Linux】线程安全——补充|互斥、锁|同步、条件变量(下)
【Linux】线程安全——补充|互斥、锁|同步、条件变量(下)
26 0
|
1月前
|
存储 安全 Linux
【Linux】线程安全——补充|互斥、锁|同步、条件变量(上)
【Linux】线程安全——补充|互斥、锁|同步、条件变量(上)
36 0
|
1月前
|
缓存 Linux 编译器
【Linux】多线程——线程概念|进程VS线程|线程控制(下)
【Linux】多线程——线程概念|进程VS线程|线程控制(下)
47 0
|
1月前
|
存储 Linux 调度
【Linux】多线程——线程概念|进程VS线程|线程控制(上)
【Linux】多线程——线程概念|进程VS线程|线程控制(上)
55 0
|
1月前
|
消息中间件 Linux
【Linux】进程间通信——system V(共享内存 | 消息队列 | 信号量)(下)
【Linux】进程间通信——system V(共享内存 | 消息队列 | 信号量)(下)
47 0