c++ - 对 pthreads 感到困惑

标签 c++ c pthreads posix

首先,我是 pthreads 的新手,所以如果我完全误解了,请告诉我。

我搜索了返回值的正确方法并找到了这个链接 How to return a value from thread in Chttps://linuxprograms.wordpress.com/category/pipes/ .

所以我可以共享由起始线程或管道信息控制的位置,但最后一个值不能放在某些堆栈上?为什么我不能像程序被 shell(例如 bash)调用时那样返回

(据我所知,如果它是 C++,则可能有一个常规的返回值,但是(根据我读到的内容,我认为这里可能是 https://computing.llnl.gov/tutorials/pthreads/)POSIX 没有完全为 C++ 定义,只是 C .)

最佳答案

看看 pthread_exit 和 pthread_join。

当你完成你的线程时,你可以调用pthread_exit(void* retval)

The pthread_exit() function terminates the calling thread and returns a value via retval that (if the thread is joinable) is available to another thread in the same process that calls pthread_join(3).

这个对 pthread_exit 的调用将停止你的线程,并且正如它所说,将返回值存储在 pthread_join 可以到达它的地方并将它放在它的第二个参数中:int pthread_join(pthread_t thread, void **retval);

当您调用 pthread_join(tid, &returnVal); 时,其中 tid 是一个 pthread_t,returnVal 现在将保存一个指向返回给 pthread_exit 的值的指针

这允许您在线程退出时将数据从线程中传递出去。

关于c++ - 对 pthreads 感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21634547/

相关文章:

c++ - 重载的构造函数对于移动和复制是非法的

c - 如何预加载共享库并使用在同一包装函数中使用 malloc 的函数来包装 malloc?

c - 是否有命令告诉编译器打印其版本?

c - C 中没有通过引用调用?

c - pthread_cleanup_push 和 O2 CFLAGS

c++ - 使用 Rcpp 返回 GMP 类

c++ - 使用 GDI+ 的图层

c - PThread Create 不创建线程

c - 尝试使用线程在 C 中按顺序打印数字

c++ - 使用 NetBeans [C++] 制作安装程序