两线程竞争修改全局变量
2016-04-16 06:46
417 查看
#include <pthread.h> #include <iostream> using namespace std; int global = 0; #define NUMTHREADS 2 pthread_mutex_t mutexnum; struct thread_data{ int idx; }; struct thread_data thread_data_array[NUMTHREADS]; void * assign_value(void *param){ struct thread_data *my_data = (struct thread_data *) param; pthread_mutex_lock(&mutexnum); global = my_data->idx; cout << "start with" << global << endl; for(int i = 0; i < 1000; i++){} // do some work cout << "end with " << global << endl; pthread_mutex_unlock(&mutexnum); } int main(){ pthread_t threads[NUMTHREADS]; cout << "initial value " << global << endl; pthread_mutex_init(&mutexnum, NULL); for(int i = 0; i < NUMTHREADS; i++){ thread_data_array[i].idx = i + 1; pthread_create(&threads[i], NULL, assign_value, (void *) &thread_data_array[i]); } for(int i = 0; i < NUMTHREADS; i++) pthread_join(threads[i], NULL); cout << "final value " << global << endl; pthread_mutex_destroy(&mutexnum); pthread_exit(NULL); }定义两个线程, threads[0] 和 threads[1];
定义全局变量 int global = 0;
在函数assign_value中,更改全局变量global;
加mutex锁避免逻辑错误。
输出结果:
initial value 0
start with1
end with 1
start with2
end with 2
final value 2
相关文章推荐
- C#使用Mutex简单实现程序单实例运行的方法
- C#中的lock、Monitor、Mutex学习笔记
- 使用 golang 实现类似 pthread_barrier_t 语义的 barrier 对象 3ff0
- Linux C Phread 入门1---线程创建
- POSIX 线程库功能接口与知识点汇总
- [转载]Pthreads mutex VS Pthreads spinlock
- C++爱好者博客
- mutex,performance_schema
- 对mutex进行RAII封装
- mutex 线程访问控制
- mutex 和 spinlock 对比
- posix线程同步和boost线程同步学习笔记
- 信号量,互斥锁实现 生产者-消费者模式
- 多线程编程之信号量
- pthread线程学习笔记一
- 多线程同步之Mutex(互斥对象)
- 多线程之互斥锁
- Mutex
- Android NDK pthreads详细使用
- c++使用thread类时编译出错,对‘pthread_create’未定义的引用