【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;
}


相关文章
|
存储 Linux API
【Linux进程概念】—— 操作系统中的“生命体”,计算机里的“多线程”
在计算机系统的底层架构中,操作系统肩负着资源管理与任务调度的重任。当我们启动各类应用程序时,其背后复杂的运作机制便悄然展开。程序,作为静态的指令集合,如何在系统中实现动态执行?本文带你一探究竟!
【Linux进程概念】—— 操作系统中的“生命体”,计算机里的“多线程”
|
并行计算 Linux
Linux内核中的线程和进程实现详解
了解进程和线程如何工作,可以帮助我们更好地编写程序,充分利用多核CPU,实现并行计算,提高系统的响应速度和计算效能。记住,适当平衡进程和线程的使用,既要拥有独立空间的'兄弟',也需要在'家庭'中分享和并行的成员。对于这个世界,现在,你应该有一个全新的认识。
594 67
|
消息中间件 Linux
Linux中的System V通信标准--共享内存、消息队列以及信号量
希望本文能帮助您更好地理解和应用System V IPC机制,构建高效的Linux应用程序。
846 48
|
Linux
Linux编程: 在业务线程中注册和处理Linux信号
通过本文,您可以了解如何在业务线程中注册和处理Linux信号。正确处理信号可以提高程序的健壮性和稳定性。希望这些内容能帮助您更好地理解和应用Linux信号处理机制。
502 26
|
Linux
Linux编程: 在业务线程中注册和处理Linux信号
本文详细介绍了如何在Linux中通过在业务线程中注册和处理信号。我们讨论了信号的基本概念,并通过完整的代码示例展示了在业务线程中注册和处理信号的方法。通过正确地使用信号处理机制,可以提高程序的健壮性和响应能力。希望本文能帮助您更好地理解和应用Linux信号处理,提高开发效率和代码质量。
421 17
|
消息中间件 Linux
Linux:进程间通信(共享内存详细讲解以及小项目使用和相关指令、消息队列、信号量)
通过上述讲解和代码示例,您可以理解和实现Linux系统中的进程间通信机制,包括共享内存、消息队列和信号量。这些机制在实际开发中非常重要,能够提高系统的并发处理能力和数据通信效率。希望本文能为您的学习和开发提供实用的指导和帮助。
1235 20
|
Linux
【Linux】System V信号量详解以及semget()、semctl()和semop()函数讲解
System V信号量的概念及其在Linux中的使用,包括 `semget()`、`semctl()`和 `semop()`函数的具体使用方法。通过实际代码示例,演示了如何创建、初始化和使用信号量进行进程间同步。掌握这些知识,可以有效解决多进程编程中的同步问题,提高程序的可靠性和稳定性。
1375 19
|
运维 API 计算机视觉
深度解密协程锁、信号量以及线程锁的实现原理
深度解密协程锁、信号量以及线程锁的实现原理
473 2
|
资源调度 Linux 调度
Linux C/C++之线程基础
这篇文章详细介绍了Linux下C/C++线程的基本概念、创建和管理线程的方法,以及线程同步的各种机制,并通过实例代码展示了线程同步技术的应用。
505 0
Linux C/C++之线程基础
|
安全 Linux
Linux线程(十一)线程互斥锁-条件变量详解
Linux线程(十一)线程互斥锁-条件变量详解