1
votes

In pthread_create I can specify one message, then on run time I may get new messages that need to be passed to the thread for printing.

One way may be to create a global vector, and keep on adding messages to it. The thread will fetch that vector and scan it for new messages.
But in this way n vectors will have to be created for n threads!
Or one structure with threadid, message, and print status.

What are the possible practical ways out?

EDIT 1:

Is the following design fine or needs some improvements?

The following code will be written in a normal function which will be called by main().

  • Check if the thread (responsible for grabbing that message) is already there.

    • If yes, Push the message in that thread's queue, wake up the thread with (pthread_cond_signal()).
    • If no, create the thread, create its queue, push the message in that queue.
  • When the thread finishes reading all the messages in its queue, let it to sleep with (pthread_cond_wait()).

3

3 Answers

4
votes

If you have a global queue I would use a linked list, not a vector, and lock it with a mutex otherwise your going to get race conditions.

2
votes

Google 'pthreads producer consumer queue'. You should not need to scan for new entries - the producer/s signal the consumer thread that new entries are available.

0
votes

Make global vector as pthread specific data, so each thread will have it own copy of the data. You do not need to create N number of variables.