pthread并行计算互斥锁的使用
来源:互联网 发布:js json操作 编辑:程序博客网 时间:2024/06/08 02:56
由于pthread实现并行计算的方式是基于共享内存的,因此在多线程中共享变量的使用存在诸多同步性问题。在多个线程中对同一个变量进行读的时候可能没问题,但是在修改的时候,就有可能造成变量内容的不一致。为了解决这个问题,就需要对共享变量进行互斥的访问。
为了实现这一功能,在pthread中提供了线程锁,通过加锁和解锁就可以轻松避免上述问题,具体实例如下:
#include<iostream>#include<pthread.h>#include<stdlib.h>#include<vector>using namespace std;vector<int> vec;pthread_mutex_t mutex;int thread_count;void *hello(void* a){
int aa = (int)a; pthread_mutex_lock(&mutex); //加锁 vec.push_back(aa); pthread_mutex_unlock(&mutex); //解锁 }int main(){ pthread_t threads[4]; thread_count = 4; pthread_mutex_init(&mutex,NULL); for(int thread = 0;thread<thread_count;thread++) { pthread_create(&threads[thread],NULL,hello,(void*)thread);//hello is the function that the new thread will execute,and the thread is the parameters } cout << "I am main." << endl; cin >> thread_count; for(int i=0;i<thread_count;i++) { pthread_join(threads[i],NULL); //stop all the threads } vector<int>::iterator it; for(it=vec.begin();it!=vec.end();it++) //print the result cout<<*it<<endl; //free(threads);}
在上述代码中实现了使用多线程向vector添加元素,并在主线程中打印出来。需要说明的是,如果在hello中如果不使用互斥锁,程序运行将出现错误。可能是pthread内部对多线程进行了限制,以避免出现类似错误。
0 0
- pthread并行计算互斥锁的使用
- pthread并行计算入门
- IDLBridge并行计算的使用问题
- [并发并行]_[任务停止]_[使用Pthread的线程本地存储来停止任务执行]
- 并行计算的解药
- 并行计算的强大
- 并行计算的概念
- 并行计算的专访
- CUDA的并行计算
- 并行Pi的计算
- Delphi 的并行计算
- 使用pthread实现多线程CPU+GPU计算
- pthread并行编程
- 用于并行计算的多线程数据结构,第 2 部分: 设计不使用互斥锁的并发数据结构
- 用于并行计算的多线程数据结构,第 2 部分: 设计不使用互斥锁的并发数据结构
- 用于并行计算的多线程数据结构,第 2 部分: 设计不使用互斥锁的并发数据结构
- 用于并行计算的多线程数据结构,第 2 部分: 设计不使用互斥锁的并发数据结构
- MATLAB并行计算工具箱使用
- asp.net+jQueryRotate开发幸运大转盘
- java基础——IO流
- 如何修改pcDuino系统默认的音频输出
- struts.xml文件中各个组件的编写顺序
- 传统BIO编程
- pthread并行计算互斥锁的使用
- Android软件开发之在程序中时时获取logcat日志信息(三十三)
- Ping 加时间戳(Windows)
- NGUI学习笔记--用法
- 二维线段树模板
- 状态量管理和绘制几何物体---1
- 最简单的方式理解“接口回调”的设计
- Android底层开发之-内核中去掉SDCard驱动后WiFi打不开
- Quick-Cocos2d-x-3.2中示例Coinfilp总结(一)