Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass overloaded method to std::thread

i am new to threading, i am trying to pass overloaded methods to std::thread like below example

#include <iostream>    
#include <thread>    

int do_calculation(int x)    
{    
   std::cout<<x;    
}    

float do_calculation(float x)    
{    
   std::cout<<x;    
}    

int main()    
{    
   std::thread t1(do_calculation,20);    
   std::thread t2(do_calculation,200.0f);    
   return 0;    
}

but the program is not compiling and throwing error that no matching function for call to 'std::thread::thread(<unresolved overloaded function type>, int)' std::thread t1(do_calculation,20);

Is there a way to call overloaded methods in thread?

like image 270
Swapnil Avatar asked Aug 30 '17 17:08

Swapnil


People also ask

Can we Overload run method of thread?

Overloading of run() method is possible. But Thread class start() method can invoke no-argument method. The other overloaded method we have to call explicitly like a normal method call.

What is the benefit using std unique_ lock between instances?

There are two primary benefits to using std::unique_lock<> over std::lock_guard<> : you can transfer ownership of the lock between instances, and. the std::unique_lock<> object does not have to own the lock on the mutex it is associated with.

What does std :: thread do?

std::thread Threads allow multiple functions to execute concurrently. std::thread objects may also be in the state that does not represent any thread (after default construction, move from, detach, or join), and a thread of execution may not be associated with any thread objects (after detach).


1 Answers

You will need to cast the functions to resolve overloading:

std::thread t1(static_cast<int(*)(int)>(do_calculation),20);    
std::thread t2(static_cast<float(*)(float)>(do_calculation),200.0f);  

Additionally, you need to either join or detach your threads lest you risk a fun trip to std::terminate:

t1.join();
t2.join();

Demo

like image 125
AndyG Avatar answered Oct 31 '22 02:10

AndyG