【问题标题】:returning a "string" from a thread从线程返回一个“字符串”
【发布时间】:2014-12-04 07:45:38
【问题描述】:

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

线程:

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

主要:

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

【问题讨论】:

    标签: c string casting pthreads return


    【解决方案1】:

    你可以这样试试

    #include <iostream>
    #include <future>
    #include <exception>
    
    std::string concatstring(const std::string& a,const std::string &b) {
        std::cout << __FUNCTION__ << "+" << std::endl;
        std::string c = a + b;
        std::cout << __FUNCTION__ << "-" << std::endl;
        return c;
        }
    
    int main() {
        try {
            std::future<std::string> fps = std::async(concatstring,"Hello","world");
            if (fps.valid()) {
                std::cout << fps.get() << std::endl;
            }
        }
        catch (const std::exception &e) {
            std::cout << "Exception: " <<e.what() << std::endl;
        }
        return 0;
    }
    

    【讨论】:

    • 该问题仅标记为与 C 相关。
    • 哦!我没看到那个标签。
    【解决方案2】:

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

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

    在主函数中使用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;
    }
    

    这就是你想要的。

    【讨论】:

    • 我强烈怀疑 OP 代码失败的根本原因是 pthread_join() 的第二个参数的错误转换。
    猜你喜欢
    • 1970-01-01
    • 2016-10-20
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 2014-10-20
    相关资源
    最近更新 更多