OpenMP未显示正确的线程编号 - C.

时间:2016-09-13 18:22:15

标签: c openmp

我有一个简单的程序,它使用openMP运行4个线程,读取4个不同的文本文件并找到字谜。我只想弄清楚为什么报告的最后一个帖子显示的是一个26478的线程数...我无法弄明白。函数countAnagrams不对tid做任何事情,它只是在函数运行完成后将它打印到屏幕上。

下面是我的代码和输出。任何帮助将不胜感激。

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

void countAnagrams(char* fileName, int threadNum);

void main ()
{
    char *fileNames[] = {"AnagramA.txt","AnagramB.txt","AnagramC.txt","AnagramD.txt"};
    int i;
    int tid;
    int nthreads = 4;
    omp_set_num_threads(nthreads);

#pragma omp parallel
{
    #pragma omp sections
    {

        #pragma omp section
            {tid = omp_get_thread_num();
            countAnagrams(fileNames[0], tid);}
        #pragma omp section
            {tid = omp_get_thread_num();
            countAnagrams(fileNames[1], tid);}
        #pragma omp section
            {tid = omp_get_thread_num();
            countAnagrams(fileNames[2], tid);}
        #pragma omp section
            {tid = omp_get_thread_num();
            countAnagrams(fileNames[3], tid);}  

    }
}
}

输出:

Filename: AnagramD.txt
Hello from thread: 1
Number of anagrams: 286
Longest anagram: 8

Filename: AnagramB.txt
Hello from thread: 0
Number of anagrams: 1148
Longest anagram: 8

Filename: AnagramC.txt
Hello from thread: 2
Number of anagrams: 5002
Longest anagram: 8

Filename: AnagramA.txt
Hello from thread: 26478
Number of anagrams: 3184
Longest anagram: 8

2 个答案:

答案 0 :(得分:1)

导致您的问题的原因是您在创建并行区域时未声明您的线程ID变量是私有的。因此,线程在那里互相踩踏,并且可能导致垃圾。要解决此问题,请确保所有应该只能由单个线程访问的变量声明为private,如下所示:

#pragma omp parallel private(tid)

答案 1 :(得分:-1)

可能导致此问题的是tid在main函数中声明。尝试按以下方式进行:``

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

void countAnagrams(char* fileName, int threadNum);

void main ()
{
char *fileNames[] = {"AnagramA.txt","AnagramB.txt","AnagramC.txt","AnagramD.txt"};
int i;

int nthreads = 4;
omp_set_num_threads(nthreads);

#pragma omp parallel private(tid) //now each thread has its private copy of tid 
{
  #pragma omp sections
   {

    #pragma omp section
        {tid = omp_get_thread_num();
        countAnagrams(fileNames[0], tid);}
    #pragma omp section
        {tid = omp_get_thread_num();
        countAnagrams(fileNames[1], tid);}
    #pragma omp section
        {tid = omp_get_thread_num();
        countAnagrams(fileNames[2], tid);}
    #pragma omp section
        {tid = omp_get_thread_num();
        countAnagrams(fileNames[3], tid);}  

   }
  }
 }