c - 带有局部变量地址的 pthread_exit() 有时有效吗?

标签 c linux multithreading ubuntu centos

我曾经遇到过 pthread_exit() 的问题。我知道没有办法像

这样使用 pthread_exit()
pthread_exit(&some_local_variable);

我们总是需要像这样使用 pthread_exit():

pthread_exit("Thread Exit Message or something necessary information");

我曾经为测试目的编写了一个简单的程序。 我做了四个线程函数,分别对两个整数进行加减乘除。然后在四个不同的线程上执行这些操作时,我试图通过 pthread_exit() 返回操作的结果。我的意思是:

pthread_exit(&add_result);

当我在 CentOS 6 中运行代码时,我得到了想要的结果(即来自所有线程的垃圾值),因为 pthread_exit() 不能那样使用。但是,我感到困惑。因为这是我第一次在 Ubuntu 11.10 中运行该代码,并从三个线程中获得了三个绝对正确的结果(正确的操作结果),并从一个线程中获得了垃圾值。这让我感到困惑,因为为什么三个线程给出正确的操作结果?

此外,我为这些线程使用了不同的休眠时间。我发现 sleep 时间最少的线程给出了垃圾值。

既然gcc是这两个操作系统的编译器,为什么一个系统会有这样的bug? 它让像我这样的新手程序员感到困惑。如果这不是错误,谁能向我解释为什么会这样?

最佳答案

我认为您的答案在 pthread_exit 文档中。你说你在 add_result 上返回了一个指针,这似乎是一个局部变量。

这是可能回答的文档的引用:

After a thread has terminated, the result of access to local (auto) variables of the thread is undefined. Thus, references to local variables of the exiting thread should not be used for the pthread_exit() value_ptr parameter value.

您可以使用线程函数的 void* 参数来使用结构,该结构应包含操作的实际结果。

关于c - 带有局部变量地址的 pthread_exit() 有时有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10027558/

相关文章:

multithreading - 在ZeroMQ中从多个线程到zmq_poll()一个REP套接字+ send()安全吗?

ios - 在多线程和两个连接上使用 FMDB

c++ - 难以阅读两行代码

objective-c - ios objC回调调用方法

linux - 使用 wc 时文件名打印两次

linux - 我如何恢复到以前的 SVN 提交?

c - ListView 控件是否有选择更改事件?

python - 数组+标量? C

linux - init.d 脚本停止 echo 管道到 grep 输出到终端

Java isAlive() 和 join()