Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Linux环形buff模拟多线程信号量操作

互斥锁mutex变量的值非0即1,只能用来表示两种状态下的临界资源。而信号量是与之类似的,用来表示可用资源的,区别在于,信号量可以表示多个可用资源的。--值为2的信号量也就是特殊的互斥锁了。那么下边就简单实现信号量表示多个资源访问的生产者消费者问题了。#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>#include <semaphore.h>
#include <pthread.h>
#define _SIZE_ 128int buf[_SIZE_];
sem_t blanks;
sem_t datas;//生产者
void *producter(void *val)
{
    int beg = 0;
    while(1)
    {
        sem_wait(&blanks);
        int data = rand()%1024;
        buf[beg] = data;        printf("%s done... data = %d ",__func__,data);
        sem_post(&datas);
        beg = (beg+1)%_SIZE_;
        sleep(3);
    }
    return NULL;
}//消费者
void *consumer(void *val)
{
    int start = 0;
    while(1)
    {
        sem_wait(&datas);
        int data = buf[start];        printf("%s dene... data = %d ", __func__,data);
        sem_post(&blanks);
        start = (start+1)%_SIZE_;
        sleep(5);
    }
    return NULL;
}int main(int argc, char const *argv[])
{
    sem_init(&blanks,0,_SIZE_);
    sem_init(&datas,0,0);    pthread_t id1,id2;
    pthread_create(&id1,NULL,producter,NULL);
    pthread_create(&id2,NULL,consumer,NULL);    pthread_join(id1,NULL);
    pthread_join(id2,NULL);    sem_destroy(&blanks);
    sem_destroy(&datas);
    return 0;
}关于互斥锁,同步等问题,参考 《Linux多线程-互斥&条件变量与同步》http://www.linuxidc.com/Linux/2016-07/133367.htm本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-07/133370.htm