【问题标题】:why are Threads loading data from array randomly?为什么线程随机从数组加载数据?
【发布时间】:2017-12-01 16:46:32
【问题描述】:

我是线程新手,我正在尝试创建一个程序,其中四个线程使用全局数组中的值进行一些并行计算。但是,线程没有按顺序加载数据的问题。

#define QUARTER 64
#define RANGE_STEP 256

struct thread_data
{
  unsigned          start;
  unsigned          stop;
  __m256*           re_fc;
  __m256*           im_fc;
};

#define         NUM_THREADS                 4
struct          thread_data                 thread_data_array[NUM_THREADS];

void *routine(void *thread_info)
{
  int n,t;
  unsigned t_start,t_stop;
  __m256 *Re_fac    , *Im_fac;
  struct thread_data *mydata;
  mydata = (struct thread_data*) thread_info;
  t_start   = mydata->start;
  t_stop    = mydata->stop;
  Re_fac        = mydata->re_fc;
  Im_fac        = mydata->im_fc;

  t = t_start;
  for (n = t_start; n < t_stop; n += 8)
  {
    // computations
    RE_m256_fac = Re_fac[t];
    IM_m256_fac = Im_fac[t]; 
    // computations
    t++;
  }
  pthread_exit(NULL);
}

int main()
{
  unsigned t,i=0;
  for(t=0;t<RANGE_STEP;t+=QUARTER)
  {
    thread_data_array[i].start      = t;
    thread_data_array[i].stop       = t+QUARTER;
    thread_data_array[i].re_fc      = RE_factors;
    thread_data_array[i].im_fc      = IM_factors;
    pthread_create(&threads[i],NULL,routine,(void *)&thread_data_array[i]);
    i++;
  }
  for(i=0; i<NUM_THREADS; i++)
  {
     int rc = pthread_join(threads[i], NULL);
     if (rc)
     {
         fprintf(stderr, "failed to join thread #%u - %s\n",i, strerror(rc));
     }
  }
}

我正在谈论的问题发生在for()循环内的线程例程中,这两个加载指令RE_m256_fac = Re_fac[t];IM_m256_fac = Im_fac[t];加载的数据不正确......我认为索引t 是一个局部变量,所以不需要同步,还是我错了?

【问题讨论】:

  • thread_data_array 是什么?
  • t 可能是一个局部变量,但它用于索引的数组thread_data_array 显然是跨线程共享的。展示它是如何构造的,并验证 routine() 中的 for 循环是否正确。
  • thread_data 类型的 thread_data_array 用于传递每个线程的参数,它被声明为全局(请参阅结构声明后的代码编辑)。我仔细检查了 routine 中的 for() 循环,它按预期工作。
  • @bnaecker : thread_data_array 不仅包含索引,还包含一堆参数,正如您在 struct 声明中看到的那样。

标签: c arrays multithreading


【解决方案1】:

经过一番挖掘后发现,由于我正在从全局共享数组中读取数据,因此我必须使用互斥机制来防止互斥:

void *routine(void *thread_info)
{
  int n,t;
  unsigned t_start,t_stop;
 __m256 *Re_fac    , *Im_fac;
 struct thread_data *mydata;
 mydata = (struct thread_data*) thread_info;
 t_start   = mydata->start;
 t_stop    = mydata->stop;
 Re_fac        = mydata->re_fc;
 Im_fac        = mydata->im_fc;

 t = t_start;
 for (n = t_start; n < t_stop; n += 8)
 {
   pthread_mutex_lock(&mutex);
   // computations
   RE_m256_fac = Re_fac[t];
   IM_m256_fac = Im_fac[t]; 
   // computations
   pthread_mutex_unlock(&mutex);
   t++;
 }
 pthread_exit(NULL);
}

从那时起,我可以看到线程正在从共享数组中正确加载值。

【讨论】:

    猜你喜欢
    • 2018-09-13
    • 1970-01-01
    • 2013-09-26
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 2021-04-30
    相关资源
    最近更新 更多