如果我在前一个线程使用时不小心调用 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/