正确地将链表节点传递给pthread函数

时间:2012-07-03 11:04:54

标签: c pthreads linked-list

请参阅下面的伪代码。代码注释应该解释我的问题。我对C中的pthreads和链表都不熟悉,所以我已经深入到了一个深层。我只需要在str函数中打印thread_work的值。顺序的代码位很好但是当每个线程完成它的工作时,它不能打印出str的值。

// linked list definition
struct linked_list {
   char *str;
   struct linked_list *next;
};

// linked list initiation
struct linked_list *root;
struct linked_list *next_info;
root = malloc( sizeof( struct linked_list ) );

// main code
some loop {
   next_node->str = str;
   printf( "%s\n", next_node ); // PRINTS FINE
   pthread_t thread;
   rc = pthread_create( &thread, NULL, thread_work, (void *) &next_node );
   next_node->next = malloc( sizeof( struct linked_list ) );
   next_node = next_node->next;
}

// code executed by each thread
void *thread_work( void *thread_arg ) {
   struct linked_list *ll;
   ll = ( struct linked_list * )thread_arg;
   printf( "%s\n", ll->str ); // PRINTS SOME MESS (��E#)
}

在我的实际代码中,还有一些linked_list struct成员。

非常感谢。

3 个答案:

答案 0 :(得分:2)

您的指针类型不匹配:您正在将指针传递给指向列表节点的指针,但在thread_work内,您将其视为指向节点的指针。在调用next_node的{​​{1}}之前移除&符号前的&符号,或按以下方式更改pthread_create

thread_work

答案 1 :(得分:0)

如果printf( "%s\n", next_node )工作正常, next_node 是一个指针,因此你不能指向 pthread_create()中的指针。 next_node 的定义会很好;)

尝试rc = pthread_create( &thread, NULL, thread_work, (void *) next_node );

答案 2 :(得分:0)

这段代码很糟糕:

// main code
some loop {
  next_node->str = str;
  printf( "%s\n", next_node ); // PRINTS FINE
  pthread_t thread;
  rc = pthread_create( &thread, NULL, thread_work, (void *) &next_node );
  next_node->next = malloc( sizeof( struct linked_list ) );
  next_node = next_node->next;
}

这里的问题是你传递的指针指向一个变量,该变量的值在调用pthread_create后立即发生变化。由于操作系统将进程克隆到新线程需要一些时间,因此实际thread_work可能(并且在大多数情况下)将在next_node = next_node->next;语句执行后启动并选择错误的值{ {1}}。您应该传递next_node的值,而不是其地址:

next_node