Linux线程间同步之信号量

1 篇文章 0 订阅

1. sem_init函数:sem是要初始化的信号量,pshared表示此信号量是在进程间共享还是线程间共享,value是信号量的初始值。

int sem_init(sem_t *sem, int pshared, unsigned int value);

2.sem_destroy函数:sem是要销毁的信号量。只有用sem_init初始化的信号量才能用sem_destroy销毁

int sem_destroy(sem_t *sem)

3.sem_wait函数:如果信号量的值为0,则线程阻塞,信号量的值大于0,将信号量的值减1,立即返回。成功返回0,失败返回-1。

int sem_wait(sem_t *sem)

4.sem_post函数:释放信号量,让信号量的值加1

int sem_post(sem_t *sem)
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#include <windows.h>
sem_t sem;
static int i = 0;

void *thread1()
{
    printf("thread_1 wait\n");
    sem_wait(&sem);
    printf("thread_1 continue run\n");
}

void *thread2()
{
    for(i = 0; i < 10; i++)
    {
        printf("thread 2 count %d\n", i);
        if(i == 5)
        {
            printf("thread 2 post\n");
            sem_post(&sem);
            usleep(10);
        }
    }
}

int main()
{
    pthread_t tid1;
    pthread_t tid2;
    int ret1 = 0;
    int ret2 = 0;
    sem_init(&sem, 0, 0);

    ret1 = pthread_create(&tid1, NULL, (void *)thread1, NULL);
    if(ret1 < 0)
        return -1;


    usleep(5000);

    ret2 = pthread_create(&tid2, NULL, (void *)thread2, NULL);
    if(ret2 < 0)
        return -1;

    usleep(10000);
    printf("end\n");
    sem_destroy(&sem);
    return 0;
}

结果:

thread_1 wait
thread 2 count 0
thread 2 count 1
thread 2 count 2
thread 2 count 3
thread 2 count 4
thread 2 count 5
thread 2 post
thread_1 continue run
thread 2 count 6
thread 2 count 7
thread 2 count 8
thread 2 count 9
end

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值