c - Second thread doesn't run until first is completed -
i'm trying implement producer/consumer type thing producer thread grabs characters out of string , puts them in circular linked list queue (5 nodes large) , consumer thread reads in characters , prints them screen. both threads stop when reach new line character. problem i'm having consumer thread never starts until producer thread terminates.
int consumer_thread_alive; ... void * producer(struct node * head) { while (consumer_thread_alive == 0) { printf("waiting on consumer."); } ... } void * consumer(struct node * head) { consumer_thread_alive = 1; ... } ... int main(int argc, char *argv[]) { ... consumer_thread_alive = 0; pthread_t produce; pthread_t consume; printf("creating producer thread.\n"); pthread_create(&produce, null, (void *) producer(&head), null ); printf("creating consumer thread.\n"); pthread_create(&consume, null, (void *) consumer(&head), null ); pthread_join(produce,null); pthread_join(consume,null); return 1; }
i cut out of other parts, thats i'm having trouble (head gets initialized earlier on in main). if run code prints out "creating producer thread." , continually prints out "waiting on consumer." until press ctrl+c , stop it. also, if remove loop in top of producer thread, run through of iterations , consumer thread gets called. whatever reason running serially instead of parallel.
change
pthread_create(&produce, null, (void *) producer(&head), null );
to be:
pthread_create(&produce, null, producer, &head);
(same consumer)
and: should test outcome of system calls!
and^2: protect concurrent access consumer_thread_alive
using mutex, example!
and^3: thread function ougth have following form:
void * thread_func(void *);
so implementation of producer's thread function may start like:
void * producer(void * pvhead) { struct node * head = pvhead; ...
but aware, passing reference the same instance of struct node
to both of threads, concurrent access inside thread functions needs protected (see and^2 above).
Comments
Post a Comment