1

请在下面查看我的伪代码。代码注释应该解释我的问题。我对 C 中的 pthreads 和链表都是新手,所以我已经跳入了深层次。我只需要str在函数中打印 out 的值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.

非常感谢。

4

3 回答 3

2

您有一个指针类型不匹配:您正在传递一个指向列表节点指针的指针,但在内部 thread_work您将其视为指向节点的指针。next_node在调用之前删除与pthread_create号,或更改thread_work如下:

void *thread_work( void *thread_arg ) {
    struct linked_list **llp, *ll;
    llp = ( struct linked_list ** )thread_arg;
    ll = *llp;
    printf( "%s\n", ll->str ); // PRINTS SOME GOOD STUFF
}
于 2012-07-03T11:08:47.003 回答
0

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

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

于 2012-07-03T11:10:02.520 回答
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;语句执行后开始并选择错误的next_node. 您应该传递 的值next_node,而不是其地址:

// main code
some loop {
  next_node->str = str;
  printf( "%s\n", next_node->str ); // PRINTS FINE
  pthread_t thread;
  rc = pthread_create( &thread, NULL, thread_work, (void *) next_node );
  // Store this thread handle somewhere safe to be able to join the thread later on
  next_node->next = malloc( sizeof( struct linked_list ) );
  next_node->next->str = next_node->next->next = NULL; // Always a good idea
  next_node = next_node->next;
}
于 2012-07-03T11:47:10.240 回答