unix互斥锁与信号量应用例子
- #include
- #include
- #include
- #include
- #include
- #include
- #define SIZE 3
- #define STR_SIZE 20
- pthread_mutex_t mutex; //全局变量对main 及 线程函数都可见
- sem_t read_sem, write_sem; //全局变量对main 及 线程函数都可见
- struct _buf_
- {
- char* buf[SIZE];
- int front, rear;
- }buffer; //循环队列结构体
- void thread(void)
- {
- while(1)
- {
- if(0 != sem_wait(&read_sem))
- {
- perror("sem_wait_0");
- exit(1);
- }
- if(0 != pthread_mutex_lock(&mutex))
- {
- perror("pthread_mutex_lock_0");
- exit(1);
- }
- fputs("output characters:\n",stdout);
- fputs(buffer.buf[buffer.front],stdout);
- buffer.front = (buffer.front + 1) % SIZE;
- if(0 != pthread_mutex_unlock(&mutex))
- {
- perror("pthread_mutex_lock_0");
- exit(1);
- }
- if(0 != sem_post(&write_sem))
- {
- perror("sem_wait_0");
- exit(1);
- }
- sleep(10);
- }
- }
- int main(void)
- {
- //初始化循环队列结构体
- int i;
- bufferbuffer.front = buffer.rear = 0;
- for(i=0; i < SIZE; i++)
- {
- buffer.buf[i] =(char*) malloc(STR_SIZE);
- }
- //初始化 互斥锁
- //存在警告 pthread_mutexattr_t mutex_attr = PTHREAD_MUTEX_INITIALIZER;
- if(0 != pthread_mutex_init(&mutex, NULL))
- {
- perror("pthread_mutex_init\n");
- exit(1);
- }
- //初始化信号量
- if(0 != sem_init(&read_sem, 0, 0))//linux进程间的信号共享还未能实现,参数PSHARE为0,而且还没有进行写操作没有数据可读,将参数vaule设置为0,进行阻塞
- {
- perror("sem_init_0\n");
- exit(1);
- }
- if(0 != sem_init(&write_sem, 0, 2))
- {
- perror("sem_init_1\n");
- exit(1);
- }
- //创建两个子线程
- pthread_t thd0,thd1;
- if(0 != pthread_create(&thd0,NULL,(void*)thread,NULL))
- {
- perror("pthread_create_0\n");
- exit(1);
- }
- if(0 != pthread_create(&thd1,NULL,(void*)thread,NULL))
- {
- perror("pthread_create_1\n");
- exit(1);
- }
- //进行写入字符操作
- while(1)
- {
- //写信号量阻塞
- if(0 != sem_wait(&write_sem))
- {
- perror("sem_wait_1");
- exit(1);
- }
- //上互斥锁所进行写入操作
- if(0 != pthread_mutex_lock(&mutex))
- {
- perror("pthread_mutex_lock_1");
- exit(1);
- }
- fputs("pls enter 20 character:\n",stdout);
- //读标准输入文件
- if(NULL == fgets(buffer.buf[buffer.rear],STR_SIZE,stdin))
- {
- perror("fgets\n");
- exit(1);
- }
- if(0 == strncmp("end\n",buffer.buf[buffer.rear],3))
- {
- printf("manual exit successfully\n");
- exit(1);
- }
- buffer.rear = (buffer.rear+1)% SIZE;
- //解互斥锁
- if(0 != pthread_mutex_unlock(&mutex))
- {
- perror("pthread_mutex_lock_1");
- exit(1);
- }
- if(0 != sem_post(&read_sem))
- {
- perror("sem_wait_1");
- exit(1);
- }
- sleep(1);
- }
- return 0;
- }
网站建设哪家好,找创新互联公司!专注于网页设计、网站建设、微信开发、微信小程序开发、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了仪陇免费建站欢迎大家使用!
附件:http://down.51cto.com/data/2362161
本文名称:unix互斥锁与信号量应用例子
文章来源:http://cdiso.cn/article/pepgcc.html