In the previous chapter we learn about mutex. In this chapter we shall learn about try_lock member function in mutex.
As explained in the previous statement, try_lock is a member function of mutex class. There are different types of try_lock functions available. They are:
There are 9 different try_lock member functions available:
1. std::try_lock
2. std::mutex::try_lock
3. std::timed_mutex::try_lock
4. std::recursive_mutex::try_lock
5. std::shared_timed_mutex::try_lock
6. std::recursive_timed_mutex::try_lock
7. std::unique_lock::try_lock
8. std::shared_mutex::try_lock
9. std::shared_lock::try_lock
In this chapter we shall learn about the 2nd variant i.e “std::mutex::try_lock”.
try_lock() is a non blocking call.
try_lock() tries to lock the mutex.
On successful lock, it will return true else it will return false.
Now what is the difference between “lock()” that we saw in previous chapter and “try_lock()”?
when 2nd thread calls “lock()” function, and if the “lock()” is acquired by previous thread, the second thread will be blocked till the first thread unlocks the resource. This is a blocking call.
But with “try_lock()”, if the 2nd thread tries to acquire lock, but the lock has been already acquired by other thread, the 2nd thread will return immediately. Thus it is a non blocking call.
Note:
If “try_lock()” is called on the same thread that owns the mutex, it will result in a undefined behaviour.
This is because, it will be a dead lock situation.
Example for mutex::try_lock
#include <iostream>
#include <mutex>
#include <thread>
// for more tutorial in C++ visit www.prodevelopertutorial.com
using namespace std;
int count = 0;
std::mutex mu;
void incrementCount()
{
if (mu.try_lock()) // try_lock()
{
count++;//critial section
cout<<count<<endl;
mu.unlock();
}
}
int main(void)
{
std::thread t1(incrementCount);
std::thread t2(incrementCount);
std::thread t3(incrementCount);
t1.join();
t2.join();
t3.join();
return 0;
}