我有2个线程来创建thread1和thread2。使用以下命令创建线程时
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);
答案 0 :(得分:5)
发出线程创建调用和线程实际开始执行之间没有关系。这一切都取决于实现,操作系统等,这就是为什么你看到两个线程实际上以看似随机的顺序开始。
如果需要线程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
}
答案 1 :(得分:3)
移动'pthread_create(& thread2,NULL,& function_th2,NULL);'到'function_th1'函数的顶部。
这肯定会实现你的要求,不需要复杂的信号。
你要求的是你真正想要或需要的是另一回事。
答案 2 :(得分:1)
我建议的解决方案之后
#include <pthread.h>
#include <stdio.h>
static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static bool wait = TRUE;
void thread_sync() {
pthread_mutex_lock(&mut);
wait = FALSE;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mut);
}
void thread_wait_sync() {
pthread_mutex_lock(&mut);
if (wait==TRUE)
{
pthread_cond_wait(&cond,&mut);
}
wait = TRUE;
pthread_mutex_unlock(&mut);
}
void *thread1(void *d) {
thread_sync();
while (1); // Rest of work happens whenever
return NULL;
}
void *thread2(void *d) {
thread_sync();
while (1);
return NULL;
}
void *thread3(void *d) {
thread_sync();
while (1);
return NULL;
}
void *thread4(void *d) {
while (1);
return NULL;
}
int main() {
pthread_t t1,t2,t3,t4;
pthread_create(&t1, NULL, thread1, NULL);
thread_wait_sync();
pthread_create(&t2, NULL, thread2, NULL);
thread_wait_sync();
pthread_create(&t3, NULL, thread3, NULL);
thread_wait_sync();
pthread_create(&t4, NULL, thread4, NULL);
while(1) {
// some work
}
}