c - C 中的 Pthread arg

标签 c linux pthreads

我正在尝试创建 n 个线程,传递整数标识符作为参数。我的问题是,当我从线程中读取该标识符时,会显示奇怪的事情。这是我的代码(简化)

  th_clientes = malloc(sizeof(int) * n_clientes);
  arg_clientes = malloc(sizeof(int) * n_clientes);
  t_espera = malloc(sizeof(int) * n_clientes);

// Create the pthread
  for (cont = 0; cont < n_clientes; ++cont) {
    arg_clientes[cont] = cont;
    pthread_create(&th_clientes[cont],NULL,clientes, &arg_clientes[cont]);
  }

  // Waiting for them.
  for (cont = 0; cont < n_clientes; ++cont) {
    pthread_join(th_clientes[cont],NULL);
  }

void *clientes(void *arg){
  int id = *(int *)arg;

  printf("Cliente %d realizando compra.\n",id);

  t_espera[id] = rand() % MAX;
  sleep(t_espera[id]);

  printf("Cliente %d saliendo del despues de espera %d.\n",id, t_espera[id]);
}

这是我输出的一部分。

Cliente 90 realizando compra.
Cliente 91 realizando compra.
Cliente 92 realizando compra.
Cliente 93 realizando compra.
Cliente 94 realizando compra.
Cliente 15 realizando compra.
Cliente 32551 realizando compra.
Cliente -189507840 realizando compra.
Cliente 32551 realizando compra.
Cliente 32551 saliendo del despues de espera 0.
Violación de segmento (`core' generado)

谢谢。

最佳答案

您可能没有为 pthread_t 数组分配足够的内存。变化:

th_clientes = malloc(sizeof(int) * n_clientes);

至:

th_clientes = malloc(sizeof(pthread_t) * n_clientes);

关于c - C 中的 Pthread arg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28482469/

相关文章:

linux - 为什么这个 C++11 程序不会死锁?

linux - 使用 `sh` 和 `source` 有什么区别?

c++ - Qt Creator 找不到 openCV 库

c - 如何验证线程创建(C 程序)

c - 使用 scanf 进入声明的第三个数组时程序崩溃

c - 段错误检查 strcmp

c - 使用复合文字初始化指向结构的指针

c - SDL 音频回拨不起作用?

linux - Windows下执行时需要修改.sh文件吗?

c - 为什么多个线程得到相同的 "tid?"