-2

I have an existing class with an function

void Foo::startSimulation(std::string system_cmd)
{
        //Calling a simulation script from system
        //After simulation, there is nothing to do. 
        //Thread self-terminates.
}

My goal is to make a thread which runs the Foo function. I have tried std::thread thread1(myFoo.startSimulation(message); However this returns

: error: no matching constructor for initialization of 'std::thread'
candidate constructor not viable: cannot convert argument of incomplete type 'void' to 'const std::__1::thread'

So my function returns void which the thread can´t run. How can I make the thread exist, and then run the processes the class function would do within that thread.

Is it in any way possible to make the thread.

std::thread thread1; // Creating the thread
thread1.start(myFoo.startSimulation("system cmd");
thread1.detach();

I know the above three lines of code are not working code in c++. std::thread has no .start() function.

However, is there a way to make threads behave in that way?

froffen
  • 27
  • 5
  • The thing you tried has mismatched brackets, so that can't work. Have you managed to start any code in a separate thread yet, btw? – Ulrich Eckhardt Jun 22 '18 at 19:22

1 Answers1

2

The correct syntax is:

std::thread thread1(&Foo::startSimulation, &myFoo, "system cmd");

Alternatively, you can do:

std::thread thread1([&myFoo]() { myFoo.startSimulation("system cmd"); });

Note that in both cases it takes myFoo by pointer or reference, so that object myFoo must not be destroyed before the thread has terminated.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • This worked perfectly. Is there any way to do the same with a function? trying to run 'std::thread t1(func1, arg1, arg2)´; I keep getting an error saying "attempt to use a deleted function". Is there a way to specify where the function is like we did with the class function "&Foo::func1"? But this function is in main cpp, so something equal to "&main()::func1", but main isn´t a class so it wouldn't work. – froffen Jun 24 '18 at 09:40
  • @froffen The error says one of the arguments is non-copyable. Post another question. – Maxim Egorushkin Jun 24 '18 at 13:27