请教:pthread_create函数中的值如何返回?
时间:2005-08-25
来源:互联网
1 #include <iostream.h>;
2 #include <pthread.h>;
3
4 void * taska(int *n)
5 {
6 int a;
7 a=*(int *)n;
8 int b=a+3;
9 int *c=&
10 return c; //想将c返回到主函数中
11 }
12
13 int main(int argc,char *argv[])
14 {
15 pthread_t ThreadA;
16 int n=100;
17 int *p=&
18 int d;
19 d=*(int *)pthread_create(&ThreadA,NULL,taska,p); //将 taska函数中 指针c指向的值传给d
20 pthread_jion(ThreadA,NULL); // 是否与第二个参数有关?
21 cout << " d = " << d << endl;
22 }
编译后 19行 出 段错误
望各位大虾指教,谢谢
作者: fc16425 发布时间: 2005-08-25
我想将主函数main中创建的线程函数taska中的值返回到主函数main中,但是没有成功。代码如下:
1 #include <iostream.h>;
2 #include <pthread.h>;
3
4 void * taska(void *n)
5 {
6 int a;
7 a=*(int *)n;
8 int b=a+3;
9 int *c=&b
10 return c; //想将c返回到主函数中
11 }
12
13 int main(int argc,char *argv[])
14 {
15 pthread_t ThreadA;
16 int n=100;
17 int *p=&
18 int d;
19 d=*(int *)pthread_create(&ThreadA,NULL,taska,p); //将 taska函数中 指针c指向的值传给d
20 pthread_jion(ThreadA,NULL); // 是否与第二个参数有关?
21 cout << " d = " << d << endl;
22 }
编译后 19行 出 段错误
望各位大虾指教,谢谢
作者: fc16425 发布时间: 2005-08-25
pthread_create函数只能返回代表线程是否创建成功的0和1。
那么怎么将taska中的值返回到主函数中?要用pthread_exit吗?怎么用?
望各位大虾指教,谢谢
作者: fc16425 发布时间: 2005-08-25
#include <pthread.h>;
#include <stdlib.h>;
#include <unistd.h>;
void *thread_function(void *arg) {
int i;
for ( i=0; i<20; i++) {
printf("Thread says hi!\n"

sleep(1);
}
return NULL;
}
int main(void) {
pthread_t mythread;
if ( pthread_create( &mythread, NULL, thread_function, NULL) ) {
printf("error creating thread."

abort();
}
if ( pthread_join ( mythread, NULL ) ) {
printf("error joining thread."

abort();
}
exit(0);
}
//编译执行
$ gcc thread1.c -o thread1 -lpthread
如果你实在是要把taska()函数返回的值送到main()函数中去使用,可以定义一个全局变量,在taska()更改这个变量值,然后在main()函数中使用这个值.
建议看一下这篇文章
http://www-128.ibm.com/developerworks/cn/linux/thread/posix_thread1/index.html#N10041
POSIX线程入门很好的资料
作者: dubble 发布时间: 2005-08-26
除了全局变量,还有别的办法吗?
thread_join函数和pthread_exit函数能用于返回吗?怎么用?
作者: fc16425 发布时间: 2005-08-26
谢谢
除了全局变量,还有别的办法吗?
thread_join函数和pthread_exit函数能用于返回吗?怎么用?
这两个函数当然是有用的

这样:
#include <iostream>;
#include <pthread.h>;
using namespace std;
void * taska(void *n)
{
int a=*(int *)n;
int *b=new int(a+3);
pthread_exit((void*)b);
}
int main(int argc,char *argv[])
{
pthread_t ThreadA;
int n=100;
int *d;
pthread_create(&ThreadA, 0, taska, (void*)&n); //我没给你做返回值判断
pthread_join(ThreadA, (void**)&d);
cout << "d =" << *d << endl;
delete d;
}
作者: 这一次我是MJ 发布时间: 2005-08-27
这个好像不能编译通过啊.
作者: _Unix_ 发布时间: 2005-08-30

作者: ddbo 发布时间: 2008-11-01
作者: eveson 发布时间: 2008-11-02
然后在父线程pthread_join()获得
作者: kissGNU 发布时间: 2008-11-03
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28