Awesome Awesome - 2 months ago 15
C++ Question

c++ class method thread

i have a class that has a method that needs to be running continuously but also be able to receive input from user. So i thought i would make the method run separately using a thread.

the code looks something like this(just the backbone):

class SystemManager
{
private:
int command;
bool commandAcK;

bool running;

//other vars

public:

SystemManager()
{
//initialisation
}

void runningAlgorithm()
{

while (running)
{
if (commandAcK)
{
//solve command
}

//run algorithm
//print results
}

}


void readCmd()
{

cin >> command;
commandAcK = true;

}



};




int main()
{

SystemManager *SM = new SystemManager;

thread tRunning = SM->runningAlgorithm();


}


now the errors look like this:

no suitable constructor exists to convert from "
void
" to "
std::thread
"



Error C2440 'initializing': cannot convert from 'void' to 'std::thread'


i have found a new method and it doesn't give me any errors

std::thread tRunning(&SystemManager::runningAlgorithm, SystemManager());


the first thing i don't understand is that this method doesn't use an instance of the class just the generic function. How can i link it to a specific instance? I need it so it can read the values of the variables.

Secondly what does
"&"
in front of SystemManager do?

(&SystemManager::runningAlgorithm)


Thirdly is there a better way of doing it? Do you have any ideas?

Thank you in advance.

Answer

The constructor for std::thread accepts a functor, and optionally it's arguments. A functor is anything that can be "called" using operator().

Then it starts a thread and inside that thread calls your functor.

std::thread tRunning(&SystemManager::runningAlgorithm, SystemManager());  

This will call the member function SystemManager::runningAlgorithm, passing in the only argument being this (SystemManager() creates a temporary instance). Remember that member functions always accept this as the first argument.

&SystemManager::runningAlgorithm returns the address of the member function runningAlgorithm from the class SystemManager.

In modern C++ this code can be simplified (i.e. made more readable) with a lambda:

std::thread tRunning([]{ SystemManager().runningAlgorithm(); });
Comments