c - 当具有相同例程的前一个线程正在运行时,pthread_create 被多次调用

标签 c pthreads

如果我在前一个线程使用时不小心调用 pthread_create 两次,则第二个 pthread_create 调用中是否存在内存泄漏或任何其他问题(例如:为 pthread 分配的内存)相同的例程正在运行?

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;
}

感谢您的帮助/回答。

最佳答案

没有。没有内存泄漏。您可以多次调用同一个线程函数,也可以重用相同的线程标识符 (thread_id)。但请注意,您无法加入没有 ID 的线程。事实上,这是线程的常见用例之一:大型工作被分成小的、相同的 block ,并且多个线程在它们上工作。

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

关于c - 当具有相同例程的前一个线程正在运行时,pthread_create 被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37453845/

相关文章:

c++ - 寻找 C/C++ 语言和标准库规范

c - 如何使用 libimobiledevice 获取连接设备的 ECID?

c函数返回数组并将数组与另一个数组进行比较

c - Linux 从 C 程序的 pthread 重启网络

C程序栈

c - 如何在 C 中使用 rand() 函数和范围

c++ - Pthread实例变量运行类中的方法

c - pthread 根据用户输入中断线程循环

c++ - 将回调函数中的对象引用传递给 std::thread

c++ - pthread_tryjoin_np?有它的 Windows 版本吗?