Вопрос

I am working on a multithreaded program but for some reason I can't get my threads to create. When I try debugging it breaks at my pthread_join statements.

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

and the join statement is just

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

Does anyone have any advice?

Это было полезно?

Решение 2

This should fix the issue

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

Другие советы

On my machine(suse 11), pthread_attr_t is defined like this:

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

the structure of the attribute type is not exposed on purpose. I guess you just declared a local pthread_attr_t object and didn't call pthread_attr_init(pthread_attr_t *attr) which initializes the thread attributes object pointed to by attr with default attribute values. So that the value of char arry in the structure is not defined, you used a uninitialized pthread_attr_t object when you create the POSIX thread. If you passes NULL as the attr argument of pthread_create(), so that the thread is created with default attributes.

At least for debugging it is a good idea to always check a system call's return value.

So modify you code like this:

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);
  }
}

This could help finding bugs.

As it seems that your code does not work when passing attr, the bug might due to no having initialised attr properly. See pthread_att_init() for more on how to initialise phtread attributes.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top