簡體   English   中英

Mutex :: try_lock()的異常行為

[英]Unexpected behavior with mutex::try_lock()

我已經在程序中嘗試過Mutex :: try_lock ()成員,該程序執行以下操作:

1)故意將互斥鎖鎖定在並行線程中。
2)在主線程中,它嘗試使用try_lock()鎖定互斥鎖。
a)如果未獲得鎖,它將在字符串中添加字符。
b)獲取鎖后,將打印字符串。

我已經在2個在線編譯器上測試了該程序:

1)在coliru上( 線程:: hardware_concurrency()為1),程序在這里

int main()
{
   /// Lock the mutex for 1 nanosecond.
   thread t {lock_mutex};

   job();

   t.join();
}


/// Lock the mutex for 1 nanosecond.
void lock_mutex()
{
   m.lock();

   this_thread::sleep_for(nanoseconds {1});

   m.unlock();
}


void job()
{
   cout << "starting job ..." << endl;

   int lock_attempts {};

   /// Try to lock the mutex.
   while (!m.try_lock())
   {
      ++lock_attempts;

      /// Lock not acquired.
      /// Append characters to the string.
      append();
   }

   /// Unlock the mutex.
   m.unlock();

   cout << "lock attempts = " << lock_attempts
        << endl;

   /// Lock acquired.
   /// Print the string.
   print();
}


/// Append characters to the string
void append()
{
   static int count = 0;

   s.push_back('a');

   /// For every 5 characters appended,
   /// append a space.
   if (++count == 5)
   {
      count = 0;
      s.push_back(' ');
   }
}


/// Print the string.
void print()
{
   cout << s << endl;
}


在這里,程序輸出是預期的:

starting job ...

lock attempts = 2444

aaaaa aaaaa aaaaa ...


但是,在這里,如果我從程序中刪除以下語句:

   cout << "starting job ..." << endl;

輸出顯示:

   lock attempts = 0

為什么會這樣?


2)另一方面,當我在ideone上嘗試該程序(甚至鎖定1秒而不是1納秒)時,在這里 -我總是得到如下輸出:

   lock attempts = 0

即使程序中存在診斷“開始作業”,也會發生這種情況。

ideone的thread :: hardware_concurrency()為8。

換句話說,我立即成功獲得了鎖。 為什么會這樣?

請注意,這不是try_lock ()虛假失敗的情況。 在這種情況下,盡管互斥鎖上存在鎖定,但成員返回false,表示鎖定嘗試失敗。

在這里,對立似乎正在發生。 盡管互斥鎖上存在一個鎖(顯然),但是該成員返回true,表示已成功獲取新的鎖! 為什么?

用std :: endl調用cout.operator <<(...)會調用flush。 這是進入內核的切換,並提供了很多時間(約納秒:))來允許lock_mutex線程運行。 當您不調用此函數時,lock_mutex尚未啟動。 由於調用了kernel,您甚至可能在單個核心系統中看到這一點。

暫無
暫無

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

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