pthread启动函数中的return()与pthread_exit()
以下程序显示了我们可以使用return
或pthread_exit
返回的状态变量void*
可用pthread_join
的变量。
是否应该优先使用一个而不是另一个?
为什么使用退货有效?通常我们考虑将return值放到堆栈上,但是由于线程完成了,堆栈应该消失了。还是直到之后堆栈才被销毁
pthread_join
?在您的工作中,您看到status变量有很多用途吗?看来我看到90%的代码只是将status参数设为NULL。由于通过
void*
ptr 进行的任何更改都已经反映在调用线程中,因此返回它似乎没有多大意义。void*
返回的任何新ptr都必须指向malloc
启动线程编辑的内容,从而使接收线程负责处理它。我认为状态变量是半毫无意义的,这是错误的吗?
这是代码:
#include <iostream>#include <pthread.h>
using namespace std;
struct taskdata
{
int x;
float y;
string z;
};
void* task1(void *data)
{
taskdata *t = (taskdata *) data;
t->x += 25;
t->y -= 4.5;
t->z = "Goodbye";
return(data);
}
void* task2(void *data)
{
taskdata *t = (taskdata *) data;
t->x -= 25;
t->y += 4.5;
t->z = "World";
pthread_exit(data);
}
int main(int argc, char *argv[])
{
pthread_t threadID;
taskdata t = {10, 10.0, "Hello"};
void *status;
cout << "before " << t.x << " " << t.y << " " << t.z << endl;
//by return()
pthread_create(&threadID, NULL, task1, (void *) &t);
pthread_join(threadID, &status);
taskdata *ts = (taskdata *) status;
cout << "after task1 " << ts->x << " " << ts->y << " " << ts->z << endl;
//by pthread_exit()
pthread_create(&threadID, NULL, task2, (void *) &t);
pthread_join(threadID, &status);
ts = (taskdata *) status;
cout << "after task2 " << ts->x << " " << ts->y << " " << ts->z << endl;
}
输出为:
before 10 10 Helloafter task1 35 5.5 Goodbye
after task2 10 10 World
回答:
(1)在C 代码中,using
return
导致pthread_exit
取消堆栈堆栈和销毁局部变量,而只能保证调用已注册的取消处理程序pthread_cancel_push()
。在某些系统上,此机制还将导致调用C
局部变量的析构函数,但是对于可移植代码而言,这是不能保证的—查看平台文档。
此外,在main()
,return
将隐式调用exit()
,从而终止程序,而pthread_exit()
只会终止线程,程序将继续运行,直到所有线程终止或某个线程调用exit()
,abort()
或终止程序的另一功能。
(2)使用return
作品,因为POSIX规范是这样说的。返回的值存储在pthread_join()
可以检索它的地方。在pthread_join()
调用之前,不会回收线程使用的资源。
(3)我从不在原始POSIX线程中使用线程的返回值。但是,我倾向于使用更高级别的工具,例如Boost线程库,以及最近使用的C ++
0x线程库,它们提供了在线程之间传递值(例如Future)的替代方法,从而避免了与内存管理相关的问题。暗示。
以上是 pthread启动函数中的return()与pthread_exit() 的全部内容, 来源链接: utcz.com/qa/432600.html