【问题标题】:multi threaded program is blocking多线程程序阻塞
【发布时间】:2017-11-23 11:19:50
【问题描述】:

您好,我正在尝试用 C 语言编写一个多线程程序,其中我使用 4 个线程对浮点数组进行一些计算。因此,我首先创建了 4 个线程,并使用一些参数来定义线程将处理数组的哪个部分。此时程序运行良好。

现在,我尝试仅使用加载和存储指令(256 位 Intel 内在函数)。然后,程序永远不会结束,尽管线程例程似乎正在完成它们的工作。

void *routine(void *thread_info)
{
   int n;
   unsigned t_start,t_stop;
   unsigned ind1, ind2, ind3;
   float *arr_in , *arr_out;
   struct thread_data *mydata;

   mydata = (struct thread_data*) thread_info;
   t_start = mydata->start;
   t_stop  = mydata->stop;
   arr_in  = mydata->input;
   arr_out = mydata->output;

   for (n = t_start; n < t_stop; n += 8)
   {  
      ind1 = 256 + n;
      ind2 = 512 + n;

      vec_a = _mm256_load_ps((float *) (&arr_in[n   ]) );
      vec_b = _mm256_load_ps((float *) (&arr_in[ind1]) );
      vec_c = _mm256_load_ps((float *) (&arr_in[ind2]) );

      _mm256_store_ps((float *) (&arr_out[n   ]), (vec_a) );
      _mm256_store_ps((float *) (&arr_out[ind1]), (vec_b) );
      _mm256_store_ps((float *) (&arr_out[ind2]), (vec_c) );
    }   
    printf("EXECUTION FINISHED ===== Thread : %u \n",t_start);
    pthread_exit(NULL);
}

void foo(float* in,float* out)
{
   unsigned t,i=0;
   for(t=0;t<256;t+=64)
   {
      thread_data_array[i].start    = t;
      thread_data_array[i].stop = t+QUARTER;
      thread_data_array[i].input    = in;
      thread_data_array[i].output   = out;
      pthread_create(&threads[i],NULL,routine,(void*)&thread_data_array[i]);
      i++;
   }
   pthread_exit(NULL);
}

int main()
{
   float *data1;
   float *data2;

   posix_memalign((void**)&data1, 32, 1024 * sizeof(float));
   posix_memalign((void**)&data2, 32, 1024 * sizeof(float));

   Load_inputs(reals,imags);//load data into the two arrays
   foo(data1,data2);
   printf("PROGRAM EXECUTION FINISHED");
   return EXIT_SUCCESS;
}

编译很好,没有错误,但执行给了我以下信息:

EXECUTION FINISHED ===== Thread : 0 
EXECUTION FINISHED ===== Thread : 64 
EXECUTION FINISHED ===== Thread : 128 
EXECUTION FINISHED ===== Thread : 192

程序没有终止,仍然缺少PROGRAM EXECUTION FINISHED

【问题讨论】:

  • 你永远不会等待你的线程完成(你应该用pthread_join来做),还有,为什么foopthread_exit

标签: c multithreading


【解决方案1】:

在你的foo函数中,你调用pthread_exit(NULL);会立即终止主线程(foo是从主线程调用的)。这就是为什么您在输出中看不到“程序执行完成”的原因,主线程永远没有机会打印出来,因为它在foo 中终止。你想要做的是join the threads with pthread_join,这将使主线程等待其他线程完成。

【讨论】:

    猜你喜欢
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    相关资源
    最近更新 更多