OpenMP指令: 并行构造

OpenMP C/C++ 指令格式

#pragma omp

directive-name(名称)

[clause, ...](语句)

newline(换行符)

Required for all OpenMP C/C++ directives.

A valid OpenMP directive must appear after the pragma and before any clauses.

Optional. Clauses can be in any order, and repeated as necessary unless otherwise restricted.

Required. Precedes the structured block which is enclosed by this directive.

构建并行区域

并行区域是被多个线程并发执行的代码块,通过如下指令构建并行区域,这是OpenMP的基础

#pragma omp parallel [clause ...]

  • 当一个线程到达一个parallel指令时,它创建了一个线程组,并成为该组的主线程,主线程的线程编号为零。
  • 进入并行区域后,代码块将被复制,所有线程都将执行该代码。
  • 在并行区域的结尾有一个隐含的屏障,只有主线程在这一点之后继续执行。
  • 如果任何线程在并行区域内终止,则该组中的所有线程都将终止,并且在那一点之前完成的工作是未定义的。

OpenMP helloworld

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
	int nthreads, tid;
	//omp_set_num_threads(4); //设置4个线程

	/* Fork a team of threads giving them their own copies of variables */
#pragma omp parallel private(nthreads, tid)
	{
		/* Obtain thread number */
		tid = omp_get_thread_num();
		printf("Hello World from thread = %d\n", tid);

		/* Only master thread does this */
		if (tid == 0)
		{
			nthreads = omp_get_num_threads();
			printf("Number of threads = %d\n", nthreads);
		}
	}  /* All threads join master thread and disband */

	return 0;
}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值