簡體   English   中英

為什么不將互斥鎖鎖定在一個線程中而不阻止將同一互斥鎖鎖定在另一個線程中?

[英]why doesn't locking a mutex in one thread not block locking the same mutex in a different thread?

基本上,我不明白為什么運行此代碼。 我相信鎖定互斥鎖會導致其他嘗試鎖定互斥鎖的嘗試,但是事實並非如此。

#include <cstdio>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>

class Foo 
{
  public:
  Foo()
  {
    pThread = boost::make_shared< boost::thread >( [=](){
      boost::unique_lock< boost::mutex >( mtx );
      while( true )
      {   
        fprintf( stdout, "I have the mutex\n");
      }   
    } );
  }

  void bar()
  {
    boost::unique_lock< boost::mutex >( mtx );
    fprintf( stdout, "bar got the mutex\n");
  }

  private:
  boost::mutex mtx;
  boost::shared_ptr< boost::thread > pThread;
};

int main()
{
  Foo foo;
  while( true )
  {
    foo.bar();
  }
}

編輯:添加一些睡眠后的輸出,以便可以管理輸出。

bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
^C

這與我先前報告的內容不同,這是更新的代碼。 我不確定休眠線程會如何影響輸出。

#include <cstdio>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

class Foo 
{
  public:
  Foo()
  {
    pThread = boost::make_shared< boost::thread >( [=](){
      boost::unique_lock< boost::mutex >( mtx );
      while( true )
      {   
        boost::this_thread::sleep( boost::posix_time::milliseconds( 1000 ) );
        fprintf( stdout, "I have the mutex\n");
      }   
    } );
  }

  void bar()
  {
    boost::unique_lock< boost::mutex >( mtx );
    fprintf( stdout, "bar got the mutex\n");
  }

  private:
  boost::mutex mtx;
  boost::shared_ptr< boost::thread > pThread;
};

int main()
{
  Foo foo;
  while( true )
  {
    boost::this_thread::sleep( boost::posix_time::milliseconds( 1000 ) );
    foo.bar();
  }
}

您甚至都沒有鎖定互斥鎖。

boost::unique_lock< boost::mutex >( mtx );

它被解析為類型為boost::unique_lock< boost::mutex >的變量mtx聲明,並使用默認構造函數進行了初始化。 相反,您需要使用引用可鎖定對象的構造函數:

boost::unique_lock< boost::mutex > lock{mtx};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM