c - 如何强制使一个线程在c中首先执行

Vin*_*nie 0 c linux multithreading pthreads

我在 c 中创建了两个线程。我想由每个线程执行两个单独的函数。如何使一个特定的线程首先被执行。

#include <stdio.h>
#include <pthread.h>

void* function_1(void* p)
{
   // statements
}

void* function_2(void* p)
{
   // statements
}

int main(void)
{
   pthread_t id1;
   pthread_t id2;

   pthread_create(&id1, NULL, function_1, NULL);
   pthread_create(&id2, NULL, function_2, NULL);
   pthread_exit(NULL);
}
Run Code Online (Sandbox Code Playgroud)

程序启动时如何使function_1在function_2之前执行?

Sol*_*low 5

将您的主要功能更改为如下所示:

int main(void) {
    function_1(NULL);
    function_2(NULL);
}
Run Code Online (Sandbox Code Playgroud)

不是开玩笑!如果在完成function_2()之前不要开始很重要function_1(),那么这就是怎么做。任何时候你需要一个程序以某种严格的顺序做某些事情;实现这一目标的最佳方法是在同一个线程中完成所有事情。

线程确实需要不时地彼此“同步”(例如,在生产者将某些东西放入队列以供取用之前,消费者从队列中取出某些东西没有任何意义),但是如果您的线程大部分时间都没有相互独立工作,那么您可能不会从使用多个线程中获得任何好处。