【问题标题】:Data sharing in openmpopenmp 中的数据共享
【发布时间】:2013-09-09 16:51:06
【问题描述】:

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

问候, -莫赫德

【问题讨论】:

  • 在并行块外声明的数据类型是共享的(除非它是并行循环中的索引),而在并行块内声明的数据类型是私有的。看我的回答here
  • 很好的链接,谢谢,我想在不改变代码的情况下对我的程序做一些多线程,看来这是不可能的。
  • 发布您尝试并行化的代码(尝试使其可读且不要太长)。

标签: c++ multithreading openmp private sharing


【解决方案1】:

你可能想看看thread local storage

【讨论】:

    【解决方案2】:

    你可以,for example:

    #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 任务异步运行:

    Use Threads Correctly = Isolation + Asynchronous Messages

    【讨论】:

    • 我想这样做而不指定哪些标识符是私有的。我希望可以使用一些命令来执行此(私有数据)声明。
    • Memory can be declared as private in two ways。第二种是在循环内(即并行 OpenMP 指令内)声明变量,而不使用 static 关键字。
    • 你能评论一下 nthreads 驻留在哪里吗?堆栈还是堆?
    猜你喜欢
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    相关资源
    最近更新 更多