我正在使用线程,我希望线程读取一个字符串并将其返回给main,以便我可以在main中使用它。你能帮助我吗?这就是我所做的,但在输出中它显示了奇怪的字符:
主题:
char *usr=malloc(sizeof(char)*10);
[...code...]
return (void*)usr;
主:
[...code...]
char usr[10];
pthread_join(login,(void*)&usr);
printf("%s",usr);
答案 0 :(得分:4)
让我们在线程函数中分配一些内存并在该内存中复制一些字符串。
然后从线程函数返回该内存的指针。
在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;
pthread_create(&th1, NULL, incer, NULL);
pthread_join(th1, (void**)&temp);
printf("temp is %s",temp);
return 0;
}
这就是你想要的。
答案 1 :(得分:0)
您可以这样尝试
#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;
}