我想知道为什么
pthread_join(pthread_self(),NULL)
会导致未定义的行为,但 WaitForSingleObject(GetCurrentThread(),INFINITE)
没问题?
另外,如果我想替换
WaitForSingleObject(GetCurrentThread(),INFINITE)
以在 Linux 中正常工作,有什么等效的吗?
我正在尝试实现一个用 Windows 调用 Linux 编写的代码。我被困在这条线上,找不到问题的答案。
pthread_join()
等待指定线程终止。 pthread_join(pthread_self(), NULL)
将尝试等待调用者线程终止,这永远不会发生。这是明显的死锁,并且它具有定义的行为:返回EDEADLK
错误。来自 man pthread_join:
EDEADLK 检测到死锁(例如,两个线程试图相互连接);或 thread 指定调用线程。
如果需要等待多个线程终止,可以按顺序join所有线程。加入顺序并不重要。代码示例:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
static void *worker(void *arg)
{
int idx = (intptr_t)arg;
printf("thread %i: started\n", idx);
/* Some pseudo-random delay 1..1000 ms */
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 1000000l * (1 + rand() % 1000);
nanosleep(&ts, NULL);
printf("thread %i: exiting\n", idx);
return NULL;
}
int main(void)
{
srand(time(NULL));
pthread_t threads[5];
const int num_threads = sizeof(threads)/sizeof(*threads);
for (int i = 0; i < num_threads; ++i)
{
void *arg = (void *)(intptr_t)i;
int err = pthread_create(threads + i, NULL, worker, arg);
if (err != 0)
abort();
}
for (int i = 0; i < num_threads; ++i)
{
printf("main: waiting for thread %i\n", i);
int err = pthread_join(threads[i], NULL);
if (err != 0)
abort();
printf("main: thread %i terminated\n", i);
}
printf("main: all threads exited\n");
return 0;
}
可能的输出:
thread 0: started
thread 1: started
thread 2: started
main: waiting for thread 0
thread 3: started
thread 4: started
thread 0: exiting
main: thread 0 terminated
main: waiting for thread 1
thread 4: exiting
thread 1: exiting
main: thread 1 terminated
main: waiting for thread 2
thread 3: exiting
thread 2: exiting
main: thread 2 terminated
main: waiting for thread 3
main: thread 3 terminated
main: waiting for thread 4
main: thread 4 terminated
main: all threads exited