Please see my pseudo-code below. The code comments should explain my problem. I’m new to both pthreads and linked lists in C so I’ve jumped into the deep end a bit. I just need to print the value of str out in the thread_work function. The sequential bit of code is fine but when each thread does its work, it can’t print out the value of 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#)
}
In my actual code there are a few more members of the linked_list struct.
Many thanks.
You have a pointer type mismatch: you are passing a pointer to a pointer to list node, but inside
thread_workyou treat it as a pointer to node. Either remove the ampersand beforenext_nodein the call topthread_create, or change yourthread_workas follows: