从线程返回“字符串”

tes*_*ter 3 c string casting return pthreads

我正在使用线程,我希望一个线程读取一个字符串并将其返回到主线程,以便我可以在主线程中使用它。你能帮助我吗?这就是我所做的,但在输出中它显示了奇怪的字符:

线:

char *usr=malloc(sizeof(char)*10);
[...code...]
return (void*)usr;
Run Code Online (Sandbox Code Playgroud)

主要的:

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

Jee*_*tel 5

让我们在线程函数中分配一些内存并在该内存中复制一些字符串。

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

在主函数中接收该线程函数使用的返回值,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;
}
Run Code Online (Sandbox Code Playgroud)

这就是你想要的。