カンマ演算子と scoped_lock

簡便ですばらしいアイディアだと思った.ちょこちょこ応用が効きそう:

std::unique_lock<std::mutex> autolk()
{
  // cout_mutexロック済みのunique_lockを(ムーブで)返す
  return std::unique_lock<std::mutex>(cout_mutex);
}

void parallel_invoked()
{
  const std::thread::id tid = std::this_thread::get_id();
  int x, y;
  // ...
  autolk(), std::cout << tid << ":" << x << "," << y << std::endl;
  // ...
}

私なりのサンプル:

このサンプルでは正しく(スレッド間で混じらずに)cout に出力が出ると40文字になるので,それを grep(1) で無視して検証しやすくする:

$ ./autolk 4 10 0 | egrep -xv '.{40}'
No lock
2012-2012May--May20- 2015 :25:1516.63578:325:16.635815 [ [0] Hi there
1] Hi there
2012-May-20 201215:-25:May-1620. 637150:9925:16.637379 [ [31] ] Hi thereHi there

2012-May-20 15:25:16.637883 [20122-] Hi thereMay
-20 15:25:16.637900 [1] Hi there
$ ./autolk 4 10 1 | egrep -xv '.{40}'
Scoped lock
$ ./autolk 4 10 2 | egrep -xv '.{40}'
Comma lock

いいね! +1

しっかしホントC++言語さんは奥が深い症候群の狩場やでぇ...