問(wèn)題描述
特別是,我正在尋找阻塞隊(duì)列.C ++ 11中有這樣的東西嗎?如果沒(méi)有,我的其他選擇是什么?我真的不想再深入到線程級(jí)別了.太容易出錯(cuò)了.
In particular, I am looking for a blocking queue. Is there such a thing in C++11? If not, what are my other options? I really don't want to go down to the thread level myself anymore. Way too error-prone.
推薦答案
根據(jù) Diego Dagum來(lái)自 Microsoft 的 Visual C++ 團(tuán)隊(duì):
一個(gè)反復(fù)出現(xiàn)的問(wèn)題(好吧,其中之一)是關(guān)于 STL 容器的以及它們是否是線程安全的.
A recurrent question (well, one of the many) is about STL containers and whether they are thread safe.
在這里用 Stephan 的話來(lái)說(shuō),事實(shí)是它們不是,不是作為bug 但作為一個(gè)特性:擁有每個(gè) STL 的每個(gè)成員函數(shù)容器獲取內(nèi)部鎖會(huì)破壞性能.作為一個(gè)通用的、高度可重用的庫(kù),它實(shí)際上不會(huì)提供正確性之一:放置鎖的正確級(jí)別是由程序在做什么決定.從這個(gè)意義上說(shuō),個(gè)人成員函數(shù)往往不是那么正確的級(jí)別.
Taking Stephan’s words here, the reality is that they aren’t, not as a bug but as a feature: having every member function of every STL container acquiring an internal lock would annihilate performance. As a general purpose, highly reusable library, it wouldn’t actually provide correctness either: the correct level to place locks is determined by what the program is doing. In that sense, individual member functions don’t tend to be such correct level.
并行模式庫(kù) (PPL) 包括幾個(gè)容器提供對(duì)其元素的線程安全訪問(wèn):
The Parallel Patterns Library (PPL) includes several containers that provide thread-safe access to their elements:
- concurrent_vector Class 是一個(gè)序列容器類(lèi),允許隨機(jī)訪問(wèn)任何元素.它支持并發(fā)安全的追加、元素訪問(wèn)、迭代器訪問(wèn)和迭代器遍歷操作.
- concurrent_queue Class 是一個(gè)序列容器類(lèi),它允許首先-in, first-out 訪問(wèn)其元素.它支持一組有限的并發(fā)安全操作,例如 push 和 try_pop,僅舉幾例.
- The concurrent_vector Class is a sequence container class that allows random access to any element. It enables concurrency-safe append, element access, iterator access and iterator traversal operations.
- The concurrent_queue Class is a sequence container class that allows first-in, first-out access to its elements. It enables a limited set of concurrency-safe operations, such as push and try_pop, to name a few.
一些示例此處.
也很有趣:http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html.
這篇關(guān)于C++11 中是否有并發(fā)容器?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!