我有 2 个线程来创建线程 1 和线程 2。创建线程时:
pthread_create(&thread1, NULL, &function_th1, NULL);
pthread_create(&thread2, NULL, &function_th2, NULL);
thread2 在 thread1 之前启动,我正在寻找在 thread2 之前启动 thread1 的解决方案。
不寻找这个解决方案:
pthread_create(&thread2, NULL, &function_th2, NULL);
pthread_create(&thread1, NULL, &function_th1, NULL);
最佳答案
发出线程创建调用的时间与线程实际开始执行的时间之间没有任何关系。这完全取决于实现、操作系统等。这就是为什么您会看到这两个线程实际上以看似随机的顺序启动。
如果您需要线程 1 在线程 2 之前启动,您可能对某些事件有一些数据/逻辑依赖性。在这种情况下,您应该使用条件变量来告诉线程 2 何时真正开始执行。
// condition variable
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
// associated mutex
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// state for condition variable
int shouldWait = 1;
...
void* function_th1(void* p) {
// execute something
// signal thread 2 to proceed
pthread_mutex_lock(&mutex);
shouldWait = 0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
// other stuff
}
void* function_th2(void* p) {
// wait for signal from thread 1
pthread_mutex_lock(&mutex);
while(shouldWait) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
// other stuff
}
关于c - 多线程启动安排,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10616406/