linux环形buff模拟多线程信号量操作
2016-07-20 02:35
453 查看
互斥锁mutex变量的值非0即1,只能用来表示两种状态下的临界资源。而信号量是与之类似的,用来表示可用资源的,区别在于,信号量可以表示多个可用资源的。
--值为2的信号量也就是特殊的互斥锁了。
那么下边就简单实现信号量表示多个资源访问的生产者消费者问题了。
关于互斥锁,同步等问题,参加上篇博客
《linux多线程-互斥&条件变量与同步》
--值为2的信号量也就是特殊的互斥锁了。
那么下边就简单实现信号量表示多个资源访问的生产者消费者问题了。
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <semaphore.h> #include <pthread.h> #define _SIZE_ 128 int 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\n",__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\n", __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多线程-互斥&条件变量与同步》
相关文章推荐
- linux多线程-互斥&条件变量与同步
- linux线程控制&线程分离
- Linux之进程
- linux 体系结构知识 博客
- <Linux> 小册子
- 云服务器 ECS Linux 系统添加“回收站”
- 云服务器 ECS Linux 系统 CPU 占用率较高问题排查思路
- 云服务器 ECS Linux 误删除文件恢复方法介绍
- mysql官方下载安装教程(centos)
- 云服务器 ECS Linux 系统中常见的日志文件介绍
- 云服务器 ECS Linux 服务器修改时区的两种方式
- php安装ssh2扩展的方法【Linux平台】
- Linux环境下mysql5.7.13安装教程
- linux 下密码生成方法
- Linux最佳的云存储服务分析
- Linux 端口详解
- CentOS下yum安装PHP
- linux 下 安装 node.js 详细步骤
- 在CentOS-x86_64位机器下编译hadoop-2.6.0源码
- 云服务器 ECS Linux 磁盘空间满(含 innode 满)问题排查方法