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?
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.
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.
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).
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With