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; }
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~