views:

84

answers:

3

Hi

I have two threads, the main thread 'A' is responsible for message handling between a number of processes. When thread A gets a buffer full message, it should inform thread B and pass a pointer to the buffer which thread B will then process.

When thread B has finished it should inform thread A that it has finished.

How do I go about implementing this using posix threads using C on linux. I have looked at conditional variables, is this the way to go? . I'm not experienced in multi threaded programming and would like some advice on the best avenue to take.

Thanks

A: 

Yes, conditional variables and mutexes are two things you have to use when implement your solution.

You can take a look at the section "A few ways to use threads" on explanation how to do it.

skwllsp
A: 

If you relax the conditions that the buffer must be full before B starts processing it and that the buffer must be empty before A starts filling it again, then this is the classic producer-consumer problem.

If you cannot relax those conditions, then I do not see the benefit of separating the functionality between two threads. Since thread A cannot add to the buffer while thread B is processing, and thread B cannot do any processing while thread A is adding to the buffer, then all the work can be done in a single thread.

Matthew T. Staebler
Yes, I agree. However I can only start Thread 'B' when I get a buffer full message from another process running on the system. Thread 'A' is used to manage the message queues. Thread A needs to be able to determine when thread 'B' has finished processing so that it can send a message to another process running on the system. What would be the best way of doing this.Thanks
mikip
A: 

I use this queue to communicate work from producers to consumers:

http://asgaard.homelinux.org/svn/threadqueue/ You can look at that code on how it's implemented (It's using pthread condition variables) In short, do this:

struct threadqueue queue;
thread_queue_init(&queue);

Producer:

struct SomeStruct *scomePtr = malloc(...);
...

thread_queue_add(&queue,somePtr,0);

Consumer (probably in a loop):

struct threadmsg msg;

thread_queue_get(&queue,NULL,&msg); //blocks until there's a messge
struct SomeStruct *scomePtr = msg.data;
...
free(somePtr); //or however you'll manage the lifetime
nos
Note -- WOT indicates that asgaard.homelinux.org (http://www.mywot.com/en/scorecard/asgaard.homelinux.org) is not a safe site to navigate to. The may be due to the fact that it inherits from homelinux.org (http://www.mywot.com/en/scorecard/homelinux.org), which is not a safe either.
Jay Elston