我目前有 N 个线程都是打开的 udp/tcp 连接。当我从任何线程中接收到第一个数据包时,主线程(称为 N 线程)需要暂停 N 线程中的执行并在恢复 N 线程之前做一些工作。
我最初的想法是让所有 N 个线程使用一个公共互斥锁,该互斥锁等待来自主线程的 pthread_cond_broadcast。据我了解,所有 N 个线程将在调用广播时按照调度程序确定的某种顺序恢复执行,因为它们都依赖于同一个互斥锁。但是,我需要它们并行恢复。
这基本上就是我的问题的样子:
主线程:
//create N threads. Each thread is connected to a different
//location but uses the same code
//detect that one of the threads has received a packet
//tell all child threads to pause
pauseThreads();
//do some work on the first packet
resumeThreads();
//tell all child threads to resume
子线程代码:
while(true){
recv() data
//the other N-1 threads should ideally block here,
//since I'd like to process just the
//very first packet
//hopefully pauseThreads() has been called by the main
//thread by here if the first packet has been received.
//All threads should block here until the main thread
//is done processing the first packet. Once it's done
//processing, *firstPacket will be false and the if statement
//can be skipped over
//only one thread should ever access this
if(*firstPacket /*this is a global variable*/ ){
//process first packet
*firstPacket = false;
//the thread that receives the first packet should block here
}
//process same packet data in another format
}
线程需要同时重新启动的原因是速度是一个问题,我不能等待每个线程一个一个地完成自己的数据处理。我已经确定了 if 语句中的阻塞,但我想不出一种有效阻塞 N-1 个线程的方法。