Calling a return method with parameters in the background thread

Hello.

I am a bit confused about calling a return method with parameters in the background thread. I tried to do it with async:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class myClass
{
public:
   myClass(const std::string& file);
   std::string foo(std::string arg);
};


int main(int argc, const char * argv[])
{
    std::string windData = run();
    
    std::cout<<std::endl<<windData<<std::endl;
    
    return 0;
}


std::string run()
{
    std::string coords = "some string";
    
    myClass myObject("FILE_PATH");

    // Multithread implementation
    auto future = std::async(std::launch::async, & myClass::foo, myObject, coords);
    std::string myResult = future.get();
    
    return myResult;
}


However, on my Mac, the clang compiler gives me 6 errors:
No matching function for call to '__make_async_assoc_state' future;
No matching function for call to '__make_deferred_assoc_state' future;
etc.

I guess, I could implement something like this:

1
2
std::thread t1(&myClass::foo,myObject,coords);
t1.join();


However, I did not manage to find how to implement this with a method returning a string.

Thanks a lot!
Last edited on
Line 22 declares a function, not an object. Remove the parentheses.

To avoid this error in the future, start using brace-initialization where available.
Last edited on
Sorry, my mistake. It is supposed to be an object with a constructor having a string parameter. Corrected in the question.

Error still occurs.
Last edited on
Not for me:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# include <string>
struct myClass {
   std::string foo(std::string arg) { 
       return arg;
   }
};

# include <future>
std::string run() {
    myClass myObject;
    auto future = std::async(std::launch::async, 
                             &myClass::foo,
                             myObject,
                             "some string");
    return future.get();
}

# include <iostream>
# include <iomanip>
int main() {
    std::cout << std::quoted(run()) << "\n";
}


http://coliru.stacked-crooked.com/a/59bb6f2038ddaaaf
Interesting. Do you have Mac or Windows? While searching for solutions, I came across with someone saying that it may not compile specifically on Mac...
Thank you, anyways!
I also tried a different way. I have created a global variable in my myClass, returning this variable in the foo() method, and having the following run() method:

1
2
3
4
5
std::thread t1(&myClass::foo,myObject,coords);

t1.join();

myResult = myClass.getGlobalVariable();


It is not working. The global variable does not have a value when getGlobalVariable() is called. But I wonder why it is happening in this case.

Thank you!
Topic archived. No new replies allowed.