c - 多线程启动安排

标签 c linux multithreading

我有 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/

相关文章:

linux - 您如何安排多个日期的 cron 作业?

python - 使用 ThreadingMixin 停止由 BaseHTTPServer 生成的线程

java - sleep 时线程中断

iphone - libarchive 解压到指定文件夹?

c - 如何将程序输出重定向到文本文件

连接多个字符串?

multithreading - 软件线程是否包括用户线程?

c - 动态增加字符数组的维数

linux - 为什么这段代码在 bash 中不起作用?

linux - 交叉编译内核模块 : how to set configs right