歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++編程 –安全並發訪問容器元素

C++編程 –安全並發訪問容器元素

日期:2017/3/1 9:39:25   编辑:Linux編程

C++ 安全並發訪問容器元素

2014-9-24 flyfish

標准庫STL的vector, deque, list等等不是線程安全的
例如 線程1正在使用迭代器(iterator)讀vector
線程2正在對該vector進行插入操作,使vector重新分配內存,這樣就造成線程1中的迭代器失效

STL的容器
多個線程讀是安全的,在讀的過程中,不能對容器有任何寫入操作
多個線程可以同時對不同的容器做寫入操作。
不能指望任何STL實現來解決線程難題,必須手動做同步控制.

C++ 設計新思維》 下載見 http://www.linuxidc.com/Linux/2014-07/104850.htm

C++ Primer Plus 第6版 中文版 清晰有書簽PDF+源代碼 http://www.linuxidc.com/Linux/2014-05/101227.htm

讀C++ Primer 之構造函數陷阱 http://www.linuxidc.com/Linux/2011-08/40176.htm

讀C++ Primer 之智能指針 http://www.linuxidc.com/Linux/2011-08/40177.htm

讀C++ Primer 之句柄類 http://www.linuxidc.com/Linux/2011-08/40175.htm

將C語言梳理一下,分布在以下10個章節中:

  1. Linux-C成長之路(一):Linux下C編程概要 http://www.linuxidc.com/Linux/2014-05/101242.htm
  2. Linux-C成長之路(二):基本數據類型 http://www.linuxidc.com/Linux/2014-05/101242p2.htm
  3. Linux-C成長之路(三):基本IO函數操作 http://www.linuxidc.com/Linux/2014-05/101242p3.htm
  4. Linux-C成長之路(四):運算符 http://www.linuxidc.com/Linux/2014-05/101242p4.htm
  5. Linux-C成長之路(五):控制流 http://www.linuxidc.com/Linux/2014-05/101242p5.htm
  6. Linux-C成長之路(六):函數要義 http://www.linuxidc.com/Linux/2014-05/101242p6.htm
  7. Linux-C成長之路(七):數組與指針 http://www.linuxidc.com/Linux/2014-05/101242p7.htm
  8. Linux-C成長之路(八):存儲類,動態內存 http://www.linuxidc.com/Linux/2014-05/101242p8.htm
  9. Linux-C成長之路(九):復合數據類型 http://www.linuxidc.com/Linux/2014-05/101242p9.htm
  10. Linux-C成長之路(十):其他高級議題



方案1 對vector進行加鎖處理

effective STL給出的Lock框架

template<typename Container> //一個為容器獲取和釋放互斥體的模板
class Lock
{ //框架;其中的很多細節被省略了
public:
Lock(const Container& container) :c(container)
{
getMutexFor(c);
//在構造函數中獲取互斥體
}
~Lock()
{
releaseMutexFor(c);
//在析構函數中釋放它
}
private: const Container& c;
};

如果需要實現工業強度,需要做更多的工作。


方案2 微軟的Parallel Patterns Library (PPL)


看MSDN
PPL 提供的功能

1 Task Parallelism: a mechanism to execute several work items (tasks) in parallel
任務並行:一種並行執行若干工作項(任務)的機制

2 Parallel algorithms: generic algorithms that act on collections of data in parallel
並行算法:並行作用於數據集合的泛型算法

3 Parallel containers and objects: generic container types that provide safe concurrent access to their elements
並行容器和對象:提供對其元素的安全並發訪問的泛型容器類型


示例是對斐波那契數列(Fibonacci)的順序計算和並行計算的比較

順序計算是
使用 STL std::for_each 算法
結果存儲在 std::vector 對象中。

並行計算是
使用 PPL Concurrency::parallel_for_each 算法
結果存儲在 Concurrency::concurrent_vector 對象中。

// parallel-fibonacci.cpp
// compile with: /EHsc
#include <windows.h>
#include <ppl.h>
#include <concurrent_vector.h>
#include <array>
#include <vector>
#include <tuple>
#include <algorithm>
#include <iostream>


using namespace Concurrency;
using namespace std;


// Calls the provided work function and returns the number of milliseconds
// that it takes to call that function.
template <class Function>
__int64 time_call(Function&& f)
{
__int64 begin = GetTickCount();
f();
return GetTickCount() - begin;
}


// Computes the nth Fibonacci number.
int fibonacci(int n)
{
if(n < 2)
return n;
return fibonacci(n-1) + fibonacci(n-2);
}


int wmain()
{
__int64 elapsed;


// An array of Fibonacci numbers to compute.
array<int, 4> a = { 24, 26, 41, 42 };


// The results of the serial computation.
vector<tuple<int,int>> results1;


// The results of the parallel computation.
concurrent_vector<tuple<int,int>> results2;


// Use the for_each algorithm to compute the results serially.
elapsed = time_call([&]
{
for_each (a.begin(), a.end(), [&](int n) {
results1.push_back(make_tuple(n, fibonacci(n)));
});
});
wcout << L"serial time: " << elapsed << L" ms" << endl;


// Use the parallel_for_each algorithm to perform the same task.
elapsed = time_call([&]
{
parallel_for_each (a.begin(), a.end(), [&](int n) {
results2.push_back(make_tuple(n, fibonacci(n)));
});


// Because parallel_for_each acts concurrently, the results do not
// have a pre-determined order. Sort the concurrent_vector object
// so that the results match the serial version.
sort(results2.begin(), results2.end());
});
wcout << L"parallel time: " << elapsed << L" ms" << endl << endl;


// Print the results.
for_each (results2.begin(), results2.end(), [](tuple<int,int>& pair) {
wcout << L"fib(" << get<0>(pair) << L"): " << get<1>(pair) << endl;
});
}

命名空間Concurrency首字母大寫,一般命名空間全是小寫。

Copyright © Linux教程網 All Rights Reserved