c - 从线程返回 "string"

标签 c string casting pthreads return

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

主题:

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/

相关文章:

c - 如何用C语言在客户端-服务器程序中建立双向链接?

c - C 中的 char **ptr 和 char *ptr[] 有什么区别?

python - 如何在fstrings中使用.loc?

java - 分割一个悬空元字符,java?

c# - 哪个更好 - (int)value 或 value as int?

c - 在 C 中为数组编写通用打印函数

c - 这个链表没有变化,在main函数中不起作用

string - Xcode 6.3 : Swift String 'characters' property not found

java - Draw2D/GEF : How to access nested figures (e. g.,用于连接)

c - 这是什么意思 ?将变量的地址转换为 char。怎么会?