[置顶] OpenMP编程->互斥锁函数


//互斥锁同步   #pragma opm atomic   x< + or * or - or * or  / or & or | or << or >> >=expr
void test9()
{
	int sum = 0;   

	std::cout << "Before: " << sum << std::endl;  
omp_set_num_threads(3); 
#pragma omp parallel for  
	for (int i = 0; i < 20000; ++i)   
	{  
#pragma omp atomic  
		sum++;
		//cout<<"ID "<<omp_get_thread_num()<<endl;
	}  

	std::cout << "After: " << sum << std::endl;  
}

//临界区声明方法,可以对某个并行程序块进行防护。
void test10()
{
	int sum = 0;   

	std::cout << "Before: " << sum << std::endl;  

#pragma omp parallel for  
	for (int i = 0; i < 100; ++i)   
	{  
#pragma omp critical (a)  
		{  
			test9();
			sum = sum + i * 2;  
		}  
	}  

	std::cout << "After: " << sum << std::endl; 
}


/*  对for循环中的所有内容进行加锁保护,同时只能有一个线程执行for循环中的内容。  */
static omp_lock_t lock; 
void test11()
{
	omp_init_lock(&lock); // 初始化互斥锁  

#pragma omp parallel for  
	for (int i = 0; i < 5; ++i)   
	{  
		omp_set_lock(&lock); //获得互斥器   
		std::cout << omp_get_thread_num() << "+" << std::endl;  
		std::cout << omp_get_thread_num() << "-" << std::endl;  
		omp_unset_lock(&lock); //释放互斥器  
	}  

	omp_destroy_lock(&lock); //销毁互斥器  
}


你可能感兴趣的:([置顶] OpenMP编程->互斥锁函数)