本人博客地址:
http://m.shnenglu.com/pwq1989/ 今天群里姐夫推薦了個C++的Actor框架 Theron,就看了下源碼,注釋比代碼還多,業界良心。
源碼我還沒看完,就看到了他的一個叫StringPool的類,里面通過Ref來生成單例(Singleton),看了下
static void Reference();這個函數實現的時候,突然腦洞一開,為啥沒有Memory Barrier(
wiki)。
先貼一下他的代碼:
1 StringPool *StringPool::smInstance = 0;
2 Mutex StringPool::smReferenceMutex;
3 uint32_t StringPool::smReferenceCount = 0;
4
5
6 void StringPool::Reference()
7 {
8 Lock lock(smReferenceMutex);
9
10 // Create the singleton instance if this is the first reference.
11 if (smReferenceCount++ == 0)
12 {
13 IAllocator *const allocator(AllocatorManager::GetCache());
14 void *const memory(allocator->AllocateAligned(sizeof(StringPool), THERON_CACHELINE_ALIGNMENT));
15 smInstance = new (memory) StringPool();
16 }
17 }
我們先不討論這一段代碼,先看看下面的:
大家如果看過C++的Double Check Lock不可靠的這篇paper(
地址),作者給出的解決方案是這樣的:
1 // First check
2 TYPE* tmp = instance_;
3 // Insert the CPU-specific memory barrier instruction
4 // to synchronize the cache lines on multi-processor.
5 asm ("memoryBarrier");
6 if (tmp == 0) {
7 // Ensure serialization (guard
8 // constructor acquires lock_).
9 Guard<LOCK> guard (lock_);
10 // Double check.
11 tmp = instance_;
12 if (tmp == 0) {
13 tmp = new TYPE;
14 // Insert the CPU-specific memory barrier instruction
15 // to synchronize the cache lines on multi-processor.
16 asm ("memoryBarrier");
17 instance_ = tmp;
18 }
19 return tmp;
其實這兩個Memory Barrier不用全屏障,第一個用讀屏障rmb()就好了。第二個需要一個寫屏障wmb()。
我們都知道mb這個東西是為了防止CPU級別的指令亂序被發明出來的,(另一個是編譯器級別的,和本篇文章沒有多大關系,有興趣大家可以去研究下),實現也是由平臺相關的特殊指令(mfence這樣的)組成的。
之所以要寫成這樣,第二個mb()是為了防止在構造函數完成之前提前對目標賦值,但ctor還沒完成,就被掛起,然后第二個線程訪問的時候,認為已經構造完畢,進而使用不完整的數據引發奇怪的錯誤。
(第一個rmb()的作用我覺得是可有可無,加上可能是為了效率把(猜),強制刷新讀取instance_的值,防止進入第一個check去競爭那個鎖,不加也是不會有錯的,因為POSIX規定mutex之間必須保持內存的可見性,所以是不需要擔心讀到臟數據) <-- 這段是個人意見,歡迎修正。
下面就是我趴了半下午才想明白的問題。。。為啥Theron中那段代碼(第一段代碼)不需要在lock中添加mb(),后來往下翻了下,發現StringPool的構造函數是空的。。根本就沒有內存的寫入,當然就不需要wmb()了。
可見,C++的多線程編程,好難
posted on 2014-01-08 00:54
右席 閱讀(5048)
評論(0) 編輯 收藏 引用 所屬分類:
搬磚之路