0

在编写多线程程序时,默认是所有线程共享内存的数据,需要指定什么是私有的。是否可以将所有数据声明为私有?

问候,-Mohd

4

2 回答 2

0

您可能想查看线程本地存储

于 2013-09-09T16:53:41.407 回答
0

例如,您可以:

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

int main (int argc, char *argv[]) 
{
int nthreads, tid;

/* 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 */

}

但是,您不能用异步消息替换共享数据,因为不能保证 openmp 任务异步运行:

正确使用线程 = 隔离 + 异步消息

于 2013-09-09T17:17:59.113 回答