我正在使用线程,我希望线程读取一个字符串并将其返回给主线程,这样我就可以在主线程中使用它。你能帮助我吗?这就是我所做的,但在输出中它显示了奇怪的字符:
主题:
char *usr=malloc(sizeof(char)*10);
[...code...]
return (void*)usr;
主要内容:
[...code...]
char usr[10];
pthread_join(login,(void*)&usr);
printf("%s",usr);
最佳答案
让我们在线程函数中分配一些内存并在该内存中复制一些字符串。
然后从线程函数返回那 block 内存的指针。
在 main 函数中使用 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 = NULL;
pthread_create(&th1, NULL, incer, NULL);
pthread_join(th1, (void**)&temp);
printf("temp is %s",temp);
if(temp != NULL)
free(temp);
return 0;
}
这就是你想要的。
关于c - 从线程返回 "string",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26277398/