【发布时间】:2011-04-11 04:37:02
【问题描述】:
以下程序显示我们可以使用return 或pthread_exit 来返回void* 变量,该变量可用于pthread_join 的状态变量。
是否应该优先使用一个而不是另一个?
为什么使用 return 有效?通常我们认为 return 将一个值放在堆栈上,但由于线程完成,堆栈应该消失。或者直到
pthread_join之后堆栈才会被销毁?在您的工作中,您是否看到状态变量的大量使用?我看到的 90% 的代码似乎只是将状态参数设置为 NULL。由于通过
void*ptr 更改的任何内容都已反映在调用线程中,因此返回它似乎没有多大意义。返回的任何新的void*ptr 都必须指向启动线程的malloced,这使接收线程有责任处理它。我认为状态变量是半无意义的,我错了吗?
代码如下:
#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 Hello
after task1 35 5.5 Goodbye
after task2 10 10 World
【问题讨论】: