【Linux技术】linux之多线程同步互斥技术
来源:互联网 发布:算法设计与分析怎么学 编辑:程序博客网 时间:2024/06/05 03:17
1.同步机制
线程同步机制主要有:互斥量/信号量/条件变量/读写锁等。
2.技术示例
3.mystery注解
3)pthread_cond_wait()使线程阻塞
4)pthread_cond_broadcast()函数用来唤醒所有被阻塞在条件变量cond上的线程。
要注意,被唤醒后的这些线程将再次竞争相应的互斥量
5)pthread_cond_init()函数创建条件变量
2.技术示例
创建2个计数线程A和B,每次计数加1,当为偶数时,A线程计数;当为奇数时,B线程计数。
源码://thread_mutex_cond.c#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <pthread.h>#define MAX_COUNT9pthread_mutex_t mutex;pthread_cond_t cond;int count=0;void AddCount_Odd_Func(void);void AddCount_Even_Func(void);int main(){ int ret; pthread_t odd_thread,even_thread; pthread_attr_t thread_attr; count = 0; pthread_mutex_init(&mutex,NULL); pthread_cond_init(&cond,NULL); ret = pthread_attr_init(&thread_attr); if (ret != 0) { perror("Attribute Creation Failed"); exit(EXIT_FAILURE); } pthread_attr_setdetachstate(&thread_attr,PTHREAD_CREATE_DETACHED); ret=pthread_create(&odd_thread,&thread_attr,(void *)&AddCount_Odd_Func,NULL); if(ret != 0) { perror("Thread Creation Failed"); exit(EXIT_FAILURE); } ret = pthread_create(&even_thread,&thread_attr,(void *)&AddCount_Even_Func, NULL); if (ret != 0) { perror("Thread Creation Failed"); exit(EXIT_FAILURE); } while(count<MAX_COUNT); printf("Finished!\n"); pthread_cond_destroy(&cond); pthread_mutex_destroy(&mutex); return 0;}void AddCount_Odd_Func(void){ pthread_mutex_lock(&mutex); while(count<MAX_COUNT) { if(count%2==1) { count++; printf("AddCount_Odd_Func():count=%d.\n",count); pthread_cond_signal(&cond); } else pthread_cond_wait(&cond, &mutex); } pthread_mutex_unlock(&mutex);}void AddCount_Even_Func(void){ pthread_mutex_lock(&mutex); while(count<MAX_COUNT) { if(count%2==0) { count++; printf("AddCount_Even_Func():count=%d.\n",count); pthread_cond_signal(&cond); } else pthread_cond_wait(&cond, &mutex); } pthread_mutex_unlock(&mutex);}
3.mystery注解
1)示例中,创建了互斥量mutex与条件量cond。mutex用于互斥操作,cond用于在相关条件成立时进行操作
2)pthread_attr_setdetachstate()函数设置线程为分离状态3)pthread_cond_wait()使线程阻塞
4)pthread_cond_broadcast()函数用来唤醒所有被阻塞在条件变量cond上的线程。
要注意,被唤醒后的这些线程将再次竞争相应的互斥量
5)pthread_cond_init()函数创建条件变量
6)pthread_cond_signal()函数用来释放被阻塞在条件变量cond上的线程
本文出自 “成鹏致远” 博客,请务必保留此出处http://infohacker.blog.51cto.com/6751239/1155056
- 【Linux技术】linux之多线程同步互斥技术
- linux 线程同步、互斥
- Linux系统线程同步技术
- linux之多任务的同步与互斥
- linux线程互斥与同步---互斥锁
- linux线程同步与互斥
- linux线程互斥与同步
- Linux 线程同步与互斥
- linux线程互斥与同步---互斥锁
- Linux线程同步与互斥
- Linux线程的同步和互斥
- Linux线程同步与互斥
- Linux线程同步与互斥
- linux 线程互斥同步By信号量
- Linux之线程:同步与互斥
- Linux下线程同步互斥
- linux线程互斥与同步
- Linux下线程互斥与同步
- 【Linux技术】Fedora下 Mysql 安装及配置
- 【Linux技术】linux连接mysql错误解决方案
- 【Linux技术】linux之消息队列
- 【Linux技术】linux之thread错误解决方案
- 深入浅出UML类图
- 【Linux技术】linux之多线程同步互斥技术
- 【Linux技术】linux套接字技术之tcp
- linux 内核GPIO 模拟 I2C
- 【Linux技术】linux无连接编程技术
- 全面掌握Java的异常处理机制
- 【Linux技术】linux网络多路复用IO技术
- 【C/C++】exit不兼容解决方案
- Linux操作系统是如何工作的?
- 【Linux技术】linux黑客之网络嗅探底层原理