According to the documents of Boost.Thread, unlock() seems to be called by the thread which owns the mutex owns.
Requires:
The current thread owns m.
But, in my test, other thread can unlock the mutex.
include <iostream>
#include <boost/thread/thread.hpp>
boost::mutex m;
boost::mutex print_m;
void sleep(int seconds)
{
boost::this_thread::sleep_for(boost::chrono::seconds(seconds));
}
void print(const char* msg)
{
boost::mutex::scoped_lock lock(print_m);
std::cout << msg << boost::this_thread::get_id() << std::endl;
}
void lock()
{
print("Before Lock : ");
m.lock();
print("After Lock : ");
}
void unlock()
{
print("Before Unlock: ");
m.unlock();
print("After Unlock : ");
}
int main(int argc, char* argv[])
{
print("Main thread : ");
sleep(1);
boost::thread t1(lock);
sleep(1);
boost::thread t2(lock);
sleep(1);
boost::thread t3(unlock);
sleep(1);
boost::thread t4(unlock);
t1.join();
t2.join();
t3.join();
t4.join();
return 0;
}
The result is:
Main thread : 7f306a294740
Before Lock : 7f3068c6c700
After Lock : 7f3068c6c700
Before Lock : 7f306846b700
Before Unlock: 7f3067c6a700
After Unlock : 7f3067c6a700
After Lock : 7f306846b700
Before Unlock: 7f3067469700
After Unlock : 7f3067469700
(Empty lines mean 1 second passed.)
Do I understand wrong about boost mutex unlock?
P.S.
I know that mutex uses for critical section in general.
But, I hope to know what the Requires
of the document means exactly.
Note: I changed the source code to express locking behavior in more detail.)