首页 > 解决方案 > 停止主线程,直到所有其他线程完成

问题描述

我想停止主线程,直到所有其他线程完成运行。有没有办法在 C 中使用 pthreads 来做到这一点?有没有办法让主线程休眠?

这是我用来测试的代码。

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

int a = 4;

void *func(void *arg)
{
    for (int i = 0; i < 5; i++)
    {
        sleep(1);
        printf("MY TURN : %d\n", i);
    }
}

void *func_2(void *arg)
{
    for (int i = 0; i < 5; i++)
    {
        sleep(1);
        printf("YOUR TURN : %d\n", i);
    }
}

void turn()
{
    for (int i = 0; i < 5; i++)
    {
        sleep(1);
        printf("THEIR TURN : %d \n", i);
    }
}

int main()
{
    pthread_t t_id, t_id_2;

    pthread_create(&t_id, NULL, func, NULL);
    pthread_create(&t_id_2, NULL, func_2, NULL);

    turn();

    pthread_join(t_id, NULL);
    pthread_join(t_id_2, NULL);
}

代码的输出

THEIR TURN : 0
YOUR TURN : 0
MY TURN : 0
MY TURN : 1
THEIR TURN : 1
YOUR TURN : 1
MY TURN : 2
THEIR TURN : 2
YOUR TURN : 2
MY TURN : 3
THEIR TURN : 3
YOUR TURN : 3
MY TURN : 4
THEIR TURN : 4
YOUR TURN : 4

我想在运行 t_id 和 t_id_2 线程后运行 turn() (主函数中的函数)。

标签: cmultithreading

解决方案


您想要的实际上正是该pthread_join函数的作用。

来自man pthread_join

int pthread_join(pthread_t thread, void **retval);
The pthread_join() function waits for the thread specified by <thread> to terminate.
If that thread has already terminated, then pthread_join() returns immediately.
The thread specified by <thread> must be joinable.

因此,在您的main函数中,您可以在调用之前加入线程turn

pthread_t t_id, t_id_2;

pthread_create(&t_id, NULL, func, NULL);
pthread_create(&t_id_2, NULL, func_2, NULL);

pthread_join(t_id, NULL);
pthread_join(t_id_2, NULL);

turn();

return 0;

turn在线程函数完成工作后调用这种方式。


推荐阅读