请原谅我刚刚开始了解多线程的概念,我只是想知道为什么我的线程可能在加入之前就退出了。本质上,我维护一个进程 ID 的全局列表,我通过调用
迭代创建它们 if(pthread_create(&thread_id[i], NULL, function_to_execute, NULL)) {
fprintf(stderr, "error thread not created\n");
}
现在的问题是,我的所有线程在到达我的 pthread join 之前就退出了
pthread_join(thread_id[i], NULL);
它深深地嵌套在函数调用中,该调用在线程创建后直接调用。我不确定是否应该执行一些锁定或其他操作,或者添加一个附加命令以确保线程在退出之前等待 join 语句。
最佳答案
来自POSIX文档:
The pthread_join() function shall suspend execution of the calling thread until the target thread terminates, unless the target thread has already terminated. On return from a successful pthread_join() call with a non-NULL value_ptr argument, the value passed to pthread_exit() by the terminating thread shall be made available in the location referenced by value_ptr. When a pthread_join() returns successfully, the target thread has been terminated. The results of multiple simultaneous calls to pthread_join() specifying the same target thread are undefined. If the thread calling pthread_join() is canceled, then the target thread shall not be detached.
所以,不。只要满足上述要求,您无需采取任何额外措施。
关于c - 线程在加入之前退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39104425/