c - 使用 pthread_create 时如何判断是什么导致了段错误?

标签 c multithreading segmentation-fault pthreads

我在调用 pthread_create 时找不到这个段错误的原因...

GDB 正在给我 程序接收到信号 SIGSEGV,段错误。 pthread_create@@GLIBC_2.2.5 () 中的 0x00007ffff7bc741d 来自/lib64/libpthread.so.0

我将包含调用它的代码部分和包含线程正在调用的函数的代码部分。

int main(int argc, char **argv)
{
  /*
   * Declare local variables
   */
  int i, j; // LK
  pthread_t *cat[NUM_CATS]; // LK
  pthread_t *lizard[NUM_LIZARDS]; // LK


  /*
   * Check for the debugging flag (-d)
   */
  debug = 0;
  if (argc > 1)
    if (strncmp(argv[1], "-d", 2) == 0)
      debug = 1;


  /*
   * Initialize variables
   */
  numCrossingSago2MonkeyGrass = 0;
  numCrossingMonkeyGrass2Sago = 0;
  running = 1;


  /*
   * Initialize random number generator
   */
  srandom( (unsigned int)time(NULL) );


  /*
   * Initialize locks and/or semaphores
   */

  sem_init(&driveway, 0, 20); // LK

  /*
   * Create NUM_LIZARDS lizard threads
   */

  // LK
  for(i = 0; i < NUM_LIZARDS; i++) {
    pthread_create(lizard[i], NULL, lizardThread, (void *)(&i));
  }

还有pthread_create调用的函数...

void * lizardThread( void * param )
{
  int num = *(int*)param;

  if (debug)
    {
      printf("[%2d] lizard is alive\n", num);
      fflush(stdout);
    }

  while(running)
    {

      lizard_sleep(num); // LK
      sago_2_monkeyGrass_is_safe(num); // LK
      cross_sago_2_monkeyGrass(num); // LK
      lizard_eat(num); // LK
      monkeyGrass_2_sago_is_safe(num); // LK
      cross_monkeyGrass_2_sago(num); // LK

    }

  pthread_exit(NULL);
}

最佳答案

段错误很可能是因为将未初始化的线程 ID 传递给 pthread_create()。数组 lizard 未初始化。

改为使用数组:

  pthread_t lizard[NUM_LIZARDS]; // LK

  ...

  // LK
  for(i = 0; i < NUM_LIZARDS; i++) {
    pthread_create(&lizard[i], NULL, lizardThread, (void *)(&i));
  }

另外,请注意有 data race因为您将 &i 传递给所有线程。相反,您可以使用数组来解决数据争用问题。

  int arr[NUM_LIZARDS];
  for(i = 0; i < NUM_LIZARDS; i++) {
    arr[i] = i;
    pthread_create(&lizard[i], NULL, lizardThread, &arr[i]);
  }

关于c - 使用 pthread_create 时如何判断是什么导致了段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40136660/

相关文章:

c - 按位运算符如何处理 avr atmega 寄存器?

wpf - 调用线程必须是STA,因为很多UI组件都需要这个

c++ - [C++][DPDK] 创建一个正确的 "private size"字节对齐的 rte_mempool

c - 在c中使用动态分配输入字符串列表

c++ - C/C++ Python 解释器

c - 从 C 中的参数读取 Lua 表 - 堆栈级别不正确?

multithreading - Tomcat 6下Servlet中重启Apache2.4

c# - 动态使用计时器对象C#/。net

c++ - SIGSEGV 的原因可能是系统内存不足吗?

可以在 printf 中使用指向字符串的指针吗?