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;
}

相关推荐

  1. OpenMP 并行构造

    2024-03-18 02:14:01       36 阅读
  2. OpenMP:变量作用域

    2024-03-18 02:14:01       37 阅读
  3. OpenMV学习笔记

    2024-03-18 02:14:01       50 阅读
  4. 【STM32+OPENMV】矩形识别

    2024-03-18 02:14:01       44 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-18 02:14:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-18 02:14:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-18 02:14:01       82 阅读
  4. Python语言-面向对象

    2024-03-18 02:14:01       91 阅读

热门阅读

  1. UE4 虚幻4快捷键教程

    2024-03-18 02:14:01       42 阅读
  2. LeetCode 567. 字符串的排列

    2024-03-18 02:14:01       45 阅读
  3. P1807 最长路题解

    2024-03-18 02:14:01       45 阅读