c - 停止主线程,直到所有其他线程完成
问题描述
我想停止主线程,直到所有其他线程完成运行。有没有办法在 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() (主函数中的函数)。
解决方案
您想要的实际上正是该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
在线程函数完成工作后调用这种方式。
推荐阅读
- mysql - 如何在 SQL 中建立账户
- python - L += [a] 和 L.append(a) 的区别
- android - recyclerview 滚动抖动与滑动图像加载,还包含其他 recylerview、webview 和视频帧
- apache-spark - 如果 Spark 应用程序请求的内存超过集群的内存,会发生什么情况?
- tensorflow - 如何使用 TensorFlow 图像分类模型调用 Google AI Platform API
- javascript - 在搜索框上书写时遇到 axios 问题
- python - 如何在部署在 Elastic Beanstalk 上的 Django 应用程序中运行 pubmed 查询?
- dart - 使用嵌套数组列表将字符串转换为 Json
- quill - getLeaf 中的索引与 getText 中的索引不同
- java - 如何使用 rangeeekbar 按价格范围过滤 Recycler 列表视图?