【问题标题】:pthread_create () not creating threadspthread_create() 不创建线程
【发布时间】:2014-04-21 00:39:20
【问题描述】:

我正在开发一个多线程程序,但由于某种原因我无法创建我的线程。当我尝试调试时,它会在我的 pthread_join 语句处中断。

for (i = 0; i < numThreads; ++i)
{ 
  pthread_create (&(tids[i]), &attr, runnerFunction, &sValue[i]);
}

而join语句就是

for (i = 0; i < numThreads; ++i)
{
    pthread_join (tids[i], NULL);
}

有人有什么建议吗?

【问题讨论】:

  • 检查pthread函数的返回值怎么样?
  • 试试pthread_create (&amp;tids[i], NULL, runnerFunction, (void*) sValue[i]);
  • @arunmoezhi 这就是修复它的原因。我可以问为什么这有效而 pthread_attr 没有?
  • 如果在create调用中使用attr,在join调用中也应该使用

标签: multithreading pthreads


【解决方案1】:

在我的机器(suse 11)上,pthread_attr_t 的定义如下:

typedef union
{
  char __size[__SIZEOF_PTHREAD_ATTR_T];
  long int __align;
} pthread_attr_t;

属性类型的结构不是故意暴露的。我猜你只是声明了一个本地pthread_attr_t 对象,并没有调用pthread_attr_init(pthread_attr_t *attr),它用默认属性值初始化了attr 指向的线程属性对象。因此未定义结构中 char 数组的值,您在创建 POSIX 线程时使用了未初始化的 pthread_attr_t 对象。如果您将NULL 作为pthread_create() 的attr 参数传递,则使用默认属性创建线程。

【讨论】:

    【解决方案2】:

    这应该可以解决问题

    pthread_create (&tids[i], NULL, runnerFunction, (void*) sValue[i]);
    

    【讨论】:

      【解决方案3】:

      至少对于调试而言,始终检查系统调用的返回值是个好主意。

      所以修改你的代码如下:

      for (i = 0; i < numThreads; ++i)
      { 
        int result = pthread_create (&(tids[i]), &attr, runnerFunction, &sValue[i]);
        if (0 != result)
        {
          fprintf(stderr, ("pthread_create() failed with error #%d: '%s'\n", result, strerror(result));
          exit(EXIT_FAILURE);
        }
      }
      

      这有助于发现错误。

      您的代码在传递attr 时似乎不起作用,该错误可能是由于没有正确初始化attr。有关如何初始化 phtread 属性的更多信息,请参阅 pthread_att_init()

      【讨论】:

        猜你喜欢
        • 2014-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-10
        • 1970-01-01
        • 2021-01-30
        • 2015-12-10
        • 1970-01-01
        相关资源
        最近更新 更多