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();
}
void
std::thread
Error C2440 'initializing': cannot convert from 'void' to 'std::thread'
std::thread tRunning(&SystemManager::runningAlgorithm, SystemManager());
"&"
(&SystemManager::runningAlgorithm)
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(); });