pthread_create 被多次调用,而具有相同例程的前一个线程是 运行

pthread_create is called multiple times while the previous thread with same routine is running

如果我不小心调用了 pthread_create 两次,而前一个具有相同例程的线程是 运行?

static void* thread_routine(void *data)
{
   while (1) {sleep(1)}
   return NULL;
}

int main()
{
    static pthread_t thread_id;
    pthread_create(&thread_id, NULL, thread_routine, NULL);
    pthread_create(&thread_id, NULL, thread_routine, NULL);

    while (1) {//> never return <//}
    return 1;
}

感谢您的helps/answers。

没有。没有内存泄漏。您可以多次调用相同的线程函数,也可以重复使用相同的线程标识符 (thread_id)。但请注意,您不能 join 没有 ID 的线程。事实上,这是线程的常见用例之一:大型工作被分成小的、相同的块,多个线程处理它们。

顺便说一下,你不需要在主线程中有一个无限循环。如果您不需要主线程,那么只需从 main() 调用 pthread_exit(0);。 忙等待循环只是在浪费 CPU.