|
我在编一个小程序,想用pthread_exit结束一个线程,返回一个值,并用pthread_join接收这个值,打印出来。是不是pthrad_exit(*)只能返回一个整数值?帮助里也没有说啊。源程序如下:
- /*example.c*/
- #include <stdio.h>
-
- #include <pthread.h>
-
- void thread1(char s[])
-
- {
- /*b1[]="This is the thread1 return value!";返回值,原来放在这里,后来想到,还是应该放到主函数里。*/
- printf("This is a pthread1.\n");
- printf("%s\n",s);
- pthread_exit(b1); //结束线程,返回一个值。
- }
- void thread2(char s[])
-
- {
- /*b2[]="This is the thread2 return value!";同上*/
- printf("This is a pthread2.\n");
- printf("%s\n",s);
- pthread_exit(b2);
- }
- /**************main function ****************/
- int main(void)
-
- {
-
- pthread_t id1,id2;
-
- int i,ret1,ret2;
- char b1[]="This is the thread1 return value!";//线程1结束时的返回值
- char b2[]="This is the thread2 return value!";//线程2结束时的返回值
- char a1[50],s1[]="This is first thread!";
- char a2[50],s2[]="This is second thread!";
- for(i=0;i<50;i++)
- {
- a1[i]='\0';
- a2[i]='\0';
- }
- ret1=pthread_create(&id1,NULL,(void *) thread1,s1);
- ret2=pthread_create(&id2,NULL,(void *) thread2,s2);
- if(ret1!=0){
-
- printf ("Create pthread1 error!\n");
-
- exit (1);
-
- }
- pthread_join(id1,a1);
- printf("%s\n",a1);
- if(ret2!=0){
-
- printf ("Create pthread2 error!\n");
-
- exit (1);
-
- }
-
- printf("This is the main process.\n");
-
- pthread_join(id2,a2);
- printf("%s\n",a2);
-
-
- return (0);
-
- }
复制代码
运行如下:
[*****@***** c]$ gcc -g -lpthread -o example example.c
example.c: In function `thread1':
example.c:13: `b1' undeclared (first use in this function)
example.c:13: (Each undeclared identifier is reported only once
example.c:13: for each function it appears in.)
example.c: In function `thread2':
example.c:21: `b2' undeclared (first use in this function)
example.c: In function `main':
example.c:50: warning: passing arg 2 of `pthread_join' from incompatible pointer
type
example.c:62: warning: passing arg 2 of `pthread_join' from incompatible pointer
type
我不明白的地方:b1[],b2[] 都是主函数里定义的的,;两个线程函数里不能用吗?而且b1[],b2[]放到各个线程函数里,后面两个警告也是会出现的,打印也不对。请教各位大虾了。 |
|