Passing reference to a thread?

Started by
0 comments, last by DividedByZero 7 years, 4 months ago
Hi Guys,

I am trying to pass a reference to a variable to a thread to use as a semaphore along with mutex. But I get this error;

Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'


This is my code;

// The thread code
void task1(bool& semaphore)
{
while (true)
{
if (semaphore)
{
std::cout << "Test\r\n";
mtx.lock();
semaphore = false;
mtx.unlock();
}
}
}

// Main()
int main()
{
bool handshake = false;

std::thread t1(task1, &handshake);

while (true)
{
mtx.lock();
handshake = true;
mtx.unlock();
system("pause");
}

return 0;
}
So in effect the first thread will be continuously running, and every time a key is pressed the thread will display something ("Test").

(I know there is a few things wrong here with threads never being able to 'join' etc.. But I am more worried about passing a reference to the thread function at this stage).


Can this be done with threads or would I have to use a global variable?(which is what I am trying to avoid).

Thanks in advance :)
Advertisement

I believe I have worked it out


std::thread(task1, std::ref(handshake));

This topic is closed to new replies.

Advertisement