Multi-Thread Programming
Is there a function call that can associate with a specific thread to make the thread run or wait? I have 4 threads in my开发者_StackOverflow社区 program and I am trying to figure out a way to tell any one of the threads to wait or run when I want them to.
Your question is quite general. It really comes down to: Review the pthreads documentation.
If what you want is to have thread A wait for thread B to finish, check out pthread_join()
.
If what you want is to have thread A wait until thread B says it's okay to continue, you will need a mutex and a conditional variable. Check out pthread_cond_wait()
and associated functions.
A common mechanism for handling multiple threads is a master/slave approach where one thread hands off tasks for others to perform. The crux to this style, which I think is what you're getting at, is to realize that even in the slave threads, each thread inherently has total control over its own execution. The master doesn't really "force" the other threads to do anything, the master can make a request but the slave thread must voluntarily accept direction from the master... hrm... so maybe master/slave is a misnomer here... Anyway, The common solution for the slave threads is in pseudocode
while (!should_exit):
while (!have_something_to_do):
wait_for_something_to_do()
do_the_thing_i_was_waiting_for()
You can implement this strategy quite easily in C using a structure like the following (I'm resorting to pseudo-c-ish code for the example's sake though)
struct Slave {
Mutex thread_lock;
ConditionVariable thread_cv;
int exit_flag;
void (*thread_operation)();
};
void slave_thread( Slave * slave ) {
while( !exit_flag )
{
lock( thread_lock );
while( slave->thread_operation == NULL )
slave->thread_cv.wait( thread_lock );
unlock( thread_lock );
(*slave->thread_operation)(); // do the master's bidding...
}
}
void master_thread()
{
Slave slave1;
Slave slave2;
slave1.thread_operation = NULL;
slave2.thread_operation = NULL;
// create the threads. They'll immediately block on the condition variable
slave1.thread_operation = some_function_pointer;
slave2.thread_operation = some_other_function_pointer;
notify_one( slave1.thread_cv ) // Now that the function pointers are set, wake
notify_one( slave2.thread_cv ) // the slave threads
}
It's an overly simplistic example, of course, but hopefully it'll give you the general idea.
精彩评论