help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Compiler gives wrong output


From: Richard Kettlewell
Subject: Re: Compiler gives wrong output
Date: Tue, 09 Jun 2015 09:16:32 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.4 (gnu/linux)

"U.Mutlu" <for-gmane@mutluit.com> writes:
> Hi,
> on this page:
> http://en.cppreference.com/w/cpp/thread/recursive_mutex/try_lock
> they give the following C++11 example:
>
> #include <iostream>
> #include <mutex>
>
> int main()
> {
>     std::mutex test;
>     if (test.try_lock()==true) {
>         std::cout << "lock acquired" << std::endl;
>         test.unlock();    //now unlock the mutex
>     } else {
>         std::cout << "lock not acquired" << std::endl;
>     }
>
>     test.lock();    //to lock it again
>     if (test.try_lock()) {  //true can be left out
>         std::cout << "lock acquired" << std::endl;
>     } else {
>         std::cout << "lock not acquired" << std::endl;
>     }
>     test.unlock();
> }
>
> and they say it would give this output:
> Output:
> lock acquired
> lock not acquired
>
> I wonder why my compiler (g++ 4.9.2 from Debian repo) gives a different 
> output:
> lock acquired
> lock acquired
>
> Which compiler is wrong, and why?

AIUI, neither is wrong.  The code violates the preconditions of
try_lock(), and therefore results in undefined behavior.

-- 
http://www.greenend.org.uk/rjk/


reply via email to

[Prev in Thread] Current Thread [Next in Thread]