3

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.)

Anselmo Park
  • 991
  • 2
  • 10
  • 14
  • 6
    Possible duplicate of [Boost: mutex unlocking from any thread possible?](https://stackoverflow.com/questions/7371766/boost-mutex-unlocking-from-any-thread-possible) – pure cuteness Mar 15 '19 at 07:13
  • 3
    By violating function invocation requirements you are simply stepping on the undefined behavior landmine. And no, you can not write any test to figure out whether it works or not. – user7860670 Mar 15 '19 at 07:14
  • Move `std::cout << "Unlock: "` after `m.unlock()`. Otherwise it is not clear if unlock happened or not. –  Mar 15 '19 at 07:16
  • @purecuteness Thank you. I couldn't find the question. – Anselmo Park Mar 15 '19 at 08:08
  • @VTT Thank you for your advice. BTW, I cannot understand the 2nd statement meaning. (I'm not good at English.) Could you explain what it means more easily, please? – Anselmo Park Mar 15 '19 at 08:10
  • By the way, such as this question, how can I accept in stack overflow system? As I know, comments cannot be accepted. – Anselmo Park Mar 15 '19 at 08:16

0 Answers0