gpt4 book ai didi

c - Linux waitid 中__WALL 的使用

转载 作者:太空宇宙 更新时间:2023-11-04 12:27:42 24 4
gpt4 key购买 nike

此代码示例基于 Michael Burr 在 How can I wait for any/all pthreads to complete? 中的回答.

我尝试修改解决方案以改为依赖 waitid。文档说 linux 的 waitid 应该接受一个 __WALL 标志,这也应该让它在子线程上等待,但我遇到了错误(EINVAL):

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

static
void msleep(int ms)
{
struct timespec waittime;

waittime.tv_sec = (ms / 1000);
ms = ms % 1000;
waittime.tv_nsec = ms * 1000 * 1000;

nanosleep( &waittime, NULL);
}

void* threadfunc( void* c)
{
int id = (int) c;
int i = 0;

for (i = 0 ; i < 12; ++i) {
printf( "thread %d, iteration %d\n", id, i);
msleep(10);
}

return 0;
}


int main()
{
int i = 4;

for (; i; --i) {
pthread_t* tcb = malloc( sizeof(*tcb));

pthread_create( tcb, NULL, threadfunc, (void*) i);
}

msleep(40);

int r;
siginfo_t info;
while(0<=(r=waitid(P_ALL, 0, &info, WEXITED|__WALL)) || errno == EINTR)
;
printf("r=%d %m\n", r);

#if 0
pthread_exit(0);
#endif

return 0;
}

知道为什么它不起作用吗?如果不是很明显,我希望得到与 main 中的 pthread_exit(0) 相同的结果——所有线程都应该运行到完成。

最佳答案

__WALL 不能在 waitid() 中使用。

根据我读到的内容,__WALL(等待所有 child ,无论克隆还是非克隆),只能与 waitpid() 一起使用,wait3()wait4()

关于c - Linux waitid 中__WALL 的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44165495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com