多线程——线程同步
数据竞争问题
void test_2(){
int sum = 0;
#pragma omp parallel for
for(int i=0;i<100;i++){
sum += 1;
#pragma omp critical
cout<<"tid:"<<omp_get_thread_num()<<" sum:"<<sum<<endl;
}
cout<<"sum:"<<sum<<endl;
}
image.png
image.png
线程互斥同步——critical
void test_2(){
int sum = 0;
#pragma omp parallel for
for(int i=0;i<100;i++){
// 线程互斥同步,保证某一时刻只有1个线程访问操作
#pragma omp critical
{
sum += 1;
cout<<"tid:"<<omp_get_thread_num()<<" sum:"<<sum<<endl;
}
}
cout<<"sum:"<<sum<<endl;
}
image.png
线程互斥同步——atmoic
void test_3(){
int sum = 0;
#pragma omp parallel for
for(int i=0;i<100;i++){
// 线程互斥同步, 原子操作
#pragma omp atomic
sum += 1;
cout<<"tid:"<<omp_get_thread_num()<<" sum:"<<sum<<endl;
}
cout<<"sum:"<<sum<<endl;
}
image.png
线程互斥同步——线程互斥锁函数
void test_4(){
omp_lock_t lock;
omp_init_lock(&lock); // 初始化创建互斥锁
int sum = 0;
#pragma omp parallel for
for(int i=0;i<100;i++){
omp_set_lock(&lock); // 加锁
sum += 1;
cout<<"tid:"<<omp_get_thread_num()<<" sum:"<<sum<<endl;
omp_unset_lock(&lock); // 解锁
}
cout<<"sum:"<<sum<<endl;
omp_destroy_lock(&lock); // 销毁线程锁
}
image.png
reduction
void test_5(){
int a[] = {1, 3, 5, 7, 9};
int b[] = {0, 2, 4, 6, 8};
int sum = 0;
#pragma omp parallel for
for(int i=0;i<5;i++){
sum += a[i] + b[i];
printf("tid:%d %d+%d=%d sum=%d\n", omp_get_thread_num(), a[i], b[i], a[i]+b[i], sum);
}
printf("sum=%d\n", sum);
}
image.png
image.png
void test_5(){
int a[] = {1, 3, 5, 7, 9};
int b[] = {0, 2, 4, 6, 8};
int sum = 0;
#pragma omp parallel for reduction(+:sum)
for(int i=0;i<5;i++){
sum += a[i] + b[i];
printf("tid:%d %d+%d=%d sum=%d\n", omp_get_thread_num(), a[i], b[i], a[i]+b[i], sum);
}
printf("sum=%d\n", sum);
}
image.png
网友评论