【Linux】Posix信号量操作中的函数

主要函数

sem_init

#include <semaphore.h>
int sem_init(sem_t *sem, int pshared, unsigned int value);
Link with -lrt or -pthread.

sem_init函数是posix信号量操作中的函数。sem_init初始化一个地址有参数sem指定的匿名信号量,value参数指定该信号量的初始值,pshared参数指定该信号量是由进程中的线程共享,还是有进程共享,0表示该信号量由进程内的线程共享,并且放置在这个进程所有线程都可见的地址上(如全局变量,或者堆上动态分配的变量)。
如果pshared非0,表示该信号量在不同的进程间共享,它应该放置在共享的内存区域。任何进程都可以访问共享区域中的信号量并且通过函数sem_post,sem_wait进行操作

sem_post

#include <semaphore.h>
int sem_post(sem_t *sem);
Link with -lrt or -pthread.

sem_post函数增加(解锁)由sem指向的信号量。如果这个信号量变得大于0,那么另个一个处于sem_wait阻塞状态的线程或者进程可以被唤醒并且继续锁定这个信号量。

sem_wait

#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减少(锁定)sem指向的信号量,如果信号量的值大于0,那么减少操作被执行,函数立即返回。如果信号量当前的值已经为0,那么函数调用阻塞,直到信号量可以被减少(信号量被其他线程或者进程释放)或者收到一个中断信号。

例子

#include <stdio.h>  
#include <unistd.h>  
#include <stdlib.h>  
#include <string.h>  
#include <pthread.h>  
#include <semaphore.h>
sem_t sid;
void main()
{
    int res;
    pthread_t threadId;
    res = sem_init(&sid,0,0);
    if (res != 0)
    {
        printf("sem_init error.\r\n");
        return;
    }
    res = pthread_create(&threadId, NULL, thread_func1, NULL);
    if (res != 0)
    {
        printf("pthread_create thread_func1 error.\r\n");
        return;
    }
    printf("pthread_create thread_func1 OK.\r\n");
    sleep(5);
    res = pthread_create(&threadId, NULL, thread_func2, NULL);
    if (res != 0)
    {
        printf("pthread_create thread_func2 error.\r\n");
        return;
    }
    printf("pthread_create thread_func2 OK.\r\n");
    while(1)
    {
    };
}
void *thread_func1(void *arg)
{
    printf("thread_func1 wait for sem_t\r\n");
    sem_wait(&sid);
    printf("thread_func1 wait for sem_t OK\r\n");
    while(1)
    {

    }
}

void *thread_func2(void *arg)
{
    printf("thread_func2 sem_post sem_t\r\n");
    sem_post(&sid);
    printf("thread_func1 sem_post OK\r\n");
    while(1)
    {

    }
}

编译和运行结果

注意编译时需要通过-l pthread连接线程库
[2017:03:27:17:53:00]root@vickytong:/home/project# gcc -o test test.c -l pthread
[2017:03:27:17:53:02]root@vickytong:/home/project#chmod 777 test && ./test
[2017:03:27:17:53:02]pthread_create thread_func1 OK.
[2017:03:27:17:53:02]thread_func1 wait for sem_t
[2017:03:27:17:53:07]pthread_create thread_func2 OK.
[2017:03:27:17:53:07]thread_func2 sem_post sem_t
[2017:03:27:17:53:07]thread_func1 sem_post OK
[2017:03:27:17:53:07]thread_func1 wait for sem_t OK

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值