windows 在Linux中实现WaitForSingleObject(GetCurrentThread(),INFINITE)

oxcyiej7  于 2023-11-21  发布在  Windows
关注(0)|答案(1)|浏览(147)

我想知道为什么pthread_join(pthread_self(),NULL)导致未定义的行为,但WaitForSingleObject(GetCurrentThread(),INFINITE)是好的?
另外,如果我想替换WaitForSingleObject(GetCurrentThread(),INFINITE)以在Linux中正常工作,那么有什么等价物呢?
我正在尝试实现一个用Windows调用Linux编写的代码。我被困在这一行,找不到问题的答案。

vh0rcniy

vh0rcniy1#

pthread_join()等待指定的线程终止。pthread_join(pthread_self(), NULL)将尝试等待调用者线程终止,这永远不会发生。这是明显的死锁,它已经定义了行为:返回EDEADLK错误。来自man pthread_join:
EDEADLK检测到死锁(例如,两个线程试图相互连接);或线程指定调用线程。
如果需要等待多个线程终止,可以顺序加入所有线程。加入的顺序无关紧要。代码示例:

#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..999 ms */
    struct timespec ts;
    ts.tv_sec = 0;
    ts.tv_nsec = 1000000l * (1 + rand() % 999);
    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

相关问题