c - 线程在加入之前退出

标签 c multithreading thread-safety pthreads thread-synchronization

请原谅我刚刚开始了解多线程的概念,我只是想知道为什么我的线程可能在加入之前就退出了。本质上,我维护一个进程 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/

相关文章:

c++ - std::condition_variable 多次调用 notify_all

vb.net - 尝试更新线程内的GUI(从BackgroundWorker开始)

c# - 多线程-产生多个线程并等待

c - 自旋锁实现 (OSSpinLock)

python - 如何在 Mac OSX 上将 python.h 放入我的 python virtualenv 中?

c - free() 是否设置 errno?

c - 如何概括我的代码

python - 如何确保共享变量是线程安全的?

multithreading - 线程安全地更新大数据矩阵: now using millions of mutexes?

c - 递归在 C 中是如何工作的?