OpenMP编程->数据传递


//分配四个线程,做多线程for循环
void test2()
{
	const int NUMBER = 100;  
	int* dataA = new int[NUMBER];  
	int* dataB = new int[NUMBER];  
	for (int i= 0; i < NUMBER; i++)  
	{  
		dataA[i] = i+1;  
		dataB[i] = 2*(i+1);  
	}      
	long double sum = 0.0;  

	omp_set_num_threads(4);  
#pragma omp parallel for reduction(+:sum)  
	for (int i = 0; i < NUMBER;  i++)   
	{  
		sum += dataA[i] + dataB[i]; 
		cout<<omp_get_thread_num()<<" ";
	}     
	cout<<sum<<endl;  
	delete [] dataA;  
	delete [] dataB;  
}

//为每个section分配一个线程,适用于函数
void test3()
{

	//分配四个线程
	omp_set_num_threads(4);  
#pragma omp parallel
	{

#pragma omp sections 
		{
#pragma omp section

			printf("section 1 ThreadId = %d\n", omp_get_thread_num());

#pragma omp section

			printf("section 2 ThreadId = %d\n", omp_get_thread_num());

#pragma omp section

			printf("section 3 ThreadId = %d\n", omp_get_thread_num());

#pragma omp section

			printf("section 4 ThreadId = %d\n", omp_get_thread_num());

		}
	}
}

//并行内部私有,不传出。
void test4()
{
	int share_a = 10; // 共享变量  
	int share_to_private_b = 10; //通过private子句修饰该变量之后在并行区域内变为私有变量  

#pragma omp parallel   
	{   
#pragma omp for private(share_to_private_b)   
		for (int i = 0; i < share_to_private_b; ++i) //该循环变量是私有的,若为两个线程,则一个线程执行0 <= i < 5,另一个线程执行5 <= i < 10  
		{  
			std::cout << i << std::endl;  
		}  
	}  
}


//并行区域内私有,不传出。
void test5()
{

	int share_a = 10; // 共享变量  
	int share_to_private_b = 10; //通过private子句修饰该变量之后在并行区域内变为私有变量  

#pragma omp parallel for firstprivate(share_to_private_b)   
	for (int i = 0; i < 10; ++i)   
	{  
		cout<<"ID "<<omp_get_thread_num()<<"  ";
		std::cout << ++share_to_private_b << std::endl;  
	}  
	cout<<"share_to_private_b is :"<<share_to_private_b<<endl;

}


//并行区域内私有,传出
void test6()
{

	int shared_to_last_private = 1;

	omp_set_num_threads(1);  
#pragma omp parallel for lastprivate(shared_to_last_private) firstprivate(shared_to_last_private)   
	for (int i = 0; i < 10; ++i)   
	{  
		std::cout << ++shared_to_last_private << std::endl;  
	}  

	std::cout << "After: " << shared_to_last_private << std::endl;  

}


////共享 传出

void test7()
{
	int sum = 0;
omp_set_num_threads(4);  
#pragma omp parallel for shared(sum)   
	for (int i = 0; i < 10; ++i)   
	{  
		sum += i;  
		cout<<"ID "<<omp_get_thread_num()<<"  ";
		std::cout << sum << std::endl;  
	}  

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


你可能感兴趣的:(OpenMP编程->数据传递)