主要说以下两种,其余陆续更新。
一、使用critical关键字
#pragma omp critical
使用上述语句声明临界区代码,位于临界区中的代码每次只能由一个线程来执行,其余线程要在队列中等候。
编译时上述语句会被解释为对代码块儿的加锁和解锁操作。
看例子:
#include <iostream>
#include <thread>
void show_num(int num)
{
std::thread::id threadId = std::this_thread::get_id();
std::cout << "this is thread " << threadId;
std::cout << " num: " << num << std::endl;
}
int main(int argc, char** argv)
{
int a[] = { 4, 2, 5, 7, 3, 6, 19, 2, 5, 1, 7, 6, 4, 13, 3, 5, 16 };
int i=0;
#pragma omp parallel for
for (i = 0; i < 17; i++)
{
#pragma omp critical
{
show_num(a[i]);
}
}
return 0;
}
运行结果为: