2014-10-09 94 views
3

我正在使用线程,我希望线程读取一个字符串并将其返回给main,以便我可以在main中使用它。你可以帮我吗?这是我做的,但在其输出显示奇怪的字符:从线程返回一个“字符串”

螺纹:

char *usr=malloc(sizeof(char)*10); 
[...code...] 
return (void*)usr; 

主:

[...code...] 
char usr[10]; 
pthread_join(login,(void*)&usr); 
printf("%s",usr); 

回答

3

让页头中的线程函数一些内存和复制一些字符串记忆。

然后从线程函数返回该内存的指针。

在主要功能为接收线程函数使用的返回值pthread_join()需要类型转换接收器值(void**)

见下面的代码。


#include<stdio.h> 
#include<pthread.h> 
#include<string.h> 
#include<stdlib.h> 

void * 
incer(void *arg) 
{ 
    long i; 

     char * usr = malloc(25); 
     strcpy(usr,"hello world\n"); 
     return usr; 
} 


int main(void) 
{ 
    pthread_t th1, th2; 
    char * temp; 

    pthread_create(&th1, NULL, incer, NULL); 


    pthread_join(th1, (void**)&temp); 
     printf("temp is %s",temp); 
    return 0; 
} 

这是你想要的。

+1

非常感谢! – testermaster 2014-10-09 11:53:17

+0

只是一点点的解释会使这个答案upvoteable ... – alk 2014-10-09 17:02:39

+0

我强烈怀疑OP的代码失败的根本原因是'pthread_join()'的第二个参数错误的转换。 – alk 2014-10-10 07:42:52