简体   繁体   English

pThreads分段错误

[英]pThreads Segmentation Fault

This is the struct passed to thread declaration: 这是传递给线程声明的结构:

   typedef struct  {
              int rowsPerThread;                    
              int StartingRow;                     
              double co[WIDTH][HEIGHT][2];          
              uint64_t total_iters;                

      } thdata;

And here's how I use it: (notice the malloc) 这是我的使用方式:(注意malloc)

  /* data passed to each thread */
  thdata *data[threads_num];


  /* create threads */
  for (i=0; i<threads_num; i++)
  {
      data[i]=(thdata *)malloc(sizeof(thdata));
      data[i]->rowsPerThread= rowsPerThread;
      data[i]->StartingRow= i*rowsPerThread;

      for (i=i*rowsPerThread; i<rowsPerThread; i++)
      memcpy(data[i]->co[i], Coordinates[i], sizeof (Coordinates) * HEIGHT * 2);


      pthread_create(&thread[i], NULL, (void *) &threaded_calc, (void *) &data[i]);   
      free(data[i]);
  }

I think there's a problem with the malloc(). 我认为malloc()有问题。

It gives me segmentation fault. 这给了我分割错误。

The problem is that you free your data[i] in the for block, right after creation of a pthread and since you cannot know when the thread is started, it may be possible that data[i] is freed before the thread is effectively started by the scheduler . 问题是您在创建pthread之后立即在for块中freedata[i] ,并且由于您不知道thread何时启动,因此有可能在有效启动thread之前先释放 data[i]scheduler

So, you should call free inside the thread body. 因此,您应该在线程体内调用free

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM