[英]Multi-Thread Programming
是否存在可以与特定线程关联以使该线程运行或等待的函数调用? 我的程序中有4个线程,我试图找出一种方法来告诉任何一个线程在需要时等待或运行。
您的问题很笼统。 真正可以归结为:查阅pthreads文档。
如果要让线程A等待线程B完成,请签出pthread_join()
。
如果要使线程A等待直到线程B认为可以继续,则需要一个互斥量和一个条件变量。 检出pthread_cond_wait()
和相关函数。
处理多线程的一种常见机制是主/从方法,其中一个线程将任务交由其他线程执行。 我认为,要达到的这种风格的症结在于, 即使在从属线程中,每个线程也固有地完全控制自己的执行 。 主服务器并没有真正“强迫”其他线程执行任何操作,主服务器可以发出请求,但从属线程必须自愿接受主服务器的指示。 ..无论如何,从属线程的常见解决方案是伪代码
while (!should_exit):
while (!have_something_to_do):
wait_for_something_to_do()
do_the_thing_i_was_waiting_for()
您可以使用如下结构在C语言中轻松实现此策略(不过,出于示例的原因,我还是采用伪C-ish代码)
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
}
当然,这是一个过于简单的示例,但希望它将为您提供总体思路。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.