Derek81
Derek81

Reputation: 162

Future and Promise mechanism usage

I'm trying to understand the Fututre-Promise mechanism in C++. Here is the code:

#include "FuturePromise.h"

void func(std::promise<int>* p) {
    int a = 10, b = 5;
    int result = a + b;
    std::cout << "From inside the Thread...." << std::endl;     p->set_value(result);
}

void func2(std::promise<char*>* p) {
    char str[10] = "Abc";
    std::cout << "From inside the Thread...." << str <<std::endl;
    p->set_value(str);
}

int FP_main() {
    std::promise<char*> p;
    std::future<char*> f = p.get_future();
    std::thread th(func2, &p);
    char* str = f.get();
    std::cout << str << std::endl;
    th.join();
    return 0;
}

I'm trying to output the string returned by the thread function func but not getting an expected result (Abc string). What I'm doing wrong?

Upvotes: 0

Views: 193

Answers (1)

catnip
catnip

Reputation: 25388

As mentioned in the comments, you are storing a pointer to a local variable in your promise, and that goes away when func2 ends.

A simple fix (as so often with char * pointers) is to use std::promise <std::string> instead:

void func2(std::promise<std::string> *p) {
    const char *str = "Abc";
    std::cout << "From inside the Thread...." << str <<std::endl;
    p->set_value(str);
}

int main() {
    std::promise<std::string> p;
    std::future<std::string> f = p.get_future();
    std::thread th(func2, &p);
    auto str = f.get();
    std::cout << str << std::endl;
    th.join();
}

Live demo

Upvotes: 1

Related Questions