C++编程 –安全并发访问容器元素

C++编程 –安全并发访问容器元素

https://blog.csdn.net/flyfish1986/article/details/39526251

 

C++ 安全并发访问容器元素

2014-9-24 flyfish

标准库STL的vector, deque, list等等不是线程安全的
例如 线程1正在使用迭代器(iterator)读vector
线程2正在对该vector进行插入操作,使vector重新分配内存,这样就造成线程1中的迭代器失效

STL的容器
多个线程读是安全的,在读的过程中,不能对容器有任何写入操作
多个线程可以同时对不同的容器做写入操作。
不能指望任何STL实现来解决线程难题,必须手动做同步控制.

方案1 对vector进行加锁处理
 

effective STL给出的Lock框架

 
  1. template<typename Container> //一个为容器获取和释放互斥体的模板

  2. class Lock

  3. { //框架;其中的很多细节被省略了

  4. public:

  5. Lock(const Container& container) :c(container)

  6. {

  7. getMutexFor(c);

  8. //在构造函数中获取互斥体

  9. }

  10. ~Lock()

  11. {

  12. releaseMutexFor(c);

  13. //在析构函数中释放它

  14. }

  15. private: const Container& c;

  16. };



如果需要实现工业强度,需要做更多的工作。


方案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 对象中。

 
  1. // parallel-fibonacci.cpp

  2. // compile with: /EHsc

  3. #include <windows.h>

  4. #include <ppl.h>

  5. #include <concurrent_vector.h>

  6. #include <array>

  7. #include <vector>

  8. #include <tuple>

  9. #include <algorithm>

  10. #include <iostream>

  11.  
  12.  
  13. using namespace Concurrency;

  14. using namespace std;

  15.  
  16.  
  17. // Calls the provided work function and returns the number of milliseconds

  18. // that it takes to call that function.

  19. template <class Function>

  20. __int64 time_call(Function&& f)

  21. {

  22. __int64 begin = GetTickCount();

  23. f();

  24. return GetTickCount() - begin;

  25. }

  26.  
  27.  
  28. // Computes the nth Fibonacci number.

  29. int fibonacci(int n)

  30. {

  31. if(n < 2)

  32. return n;

  33. return fibonacci(n-1) + fibonacci(n-2);

  34. }

  35.  
  36.  
  37. int wmain()

  38. {

  39. __int64 elapsed;

  40.  
  41.  
  42. // An array of Fibonacci numbers to compute.

  43. array<int, 4> a = { 24, 26, 41, 42 };

  44.  
  45.  
  46. // The results of the serial computation.

  47. vector<tuple<int,int>> results1;

  48.  
  49.  
  50. // The results of the parallel computation.

  51. concurrent_vector<tuple<int,int>> results2;

  52.  
  53.  
  54. // Use the for_each algorithm to compute the results serially.

  55. elapsed = time_call([&]

  56. {

  57. for_each (a.begin(), a.end(), [&](int n) {

  58. results1.push_back(make_tuple(n, fibonacci(n)));

  59. });

  60. });

  61. wcout << L"serial time: " << elapsed << L" ms" << endl;

  62.  
  63.  
  64. // Use the parallel_for_each algorithm to perform the same task.

  65. elapsed = time_call([&]

  66. {

  67. parallel_for_each (a.begin(), a.end(), [&](int n) {

  68. results2.push_back(make_tuple(n, fibonacci(n)));

  69. });

  70.  
  71.  
  72. // Because parallel_for_each acts concurrently, the results do not

  73. // have a pre-determined order. Sort the concurrent_vector object

  74. // so that the results match the serial version.

  75. sort(results2.begin(), results2.end());

  76. });

  77. wcout << L"parallel time: " << elapsed << L" ms" << endl << endl;

  78.  
  79.  
  80. // Print the results.

  81. for_each (results2.begin(), results2.end(), [](tuple<int,int>& pair) {

  82. wcout << L"fib(" << get<0>(pair) << L"): " << get<1>(pair) << endl;

  83. });

  84. }


命名空间Concurrency首字母大写,一般命名空间全是小写。

贴一个简单的示例代码
使用parallel_for_each 算法计算std::array 对象中每个元素的平方
参数分别是lambda 函数、函数对象和函数指针。

 
  1. #include "stdafx.h"

  2. #include <ppl.h>

  3. #include <array>

  4. #include <iostream>

  5. using namespace Concurrency;

  6. using namespace std;

  7. using namespace std::tr1;

  8.  
  9.  
  10. // Function object (functor) class that computes the square of its input.

  11. template<class Ty>

  12. class SquareFunctor

  13. {

  14. public:

  15. void operator()(Ty& n) const

  16. {

  17. n *= n;

  18. }

  19. };

  20.  
  21.  
  22. // Function that computes the square of its input.

  23. template<class Ty>

  24. void square_function(Ty& n)

  25. {

  26. n *= n;

  27. }

  28. int _tmain(int argc, _TCHAR* argv[])

  29. {

  30. // Create an array object that contains 5 values.

  31. array<int, 5> values = { 1, 2, 3, 4, 5 };

  32.  
  33.  
  34. // Use a lambda function, a function object, and a function pointer to

  35. // compute the square of each element of the array in parallel.

  36.  
  37.  
  38. // Use a lambda function to square each element.

  39. parallel_for_each(values.begin(), values.end(), [](int& n){n *= n;});

  40.  
  41.  
  42. // Use a function object (functor) to square each element.

  43. parallel_for_each(values.begin(), values.end(), SquareFunctor<int>());

  44.  
  45.  
  46. // Use a function pointer to square each element.

  47. parallel_for_each(values.begin(), values.end(), &square_function<int>);

  48.  
  49.  
  50. // Print each element of the array to the console.

  51. for_each(values.begin(), values.end(), [](int& n) {

  52. wcout << n << endl;

  53. });

  54. return 0;

  55. }


在微软的concurrent_vector.h文件中有这样一句
Microsoft would like to acknowledge that this concurrency data structure implementation
is based on Intel implementation in its Threading Building Blocks ("Intel Material").
也就是微软的concurrent_vector是在Intel 的Threading Building Blocks基础上实现的。

方案3 Intel TBB(Threading Building Blocks)
 Intel TBB 提供的功能
 1 直接使用的线程安全容器,比如 concurrent_vector 和 concurrent_queue。
 2 通用的并行算法,如 parallel_for 和 parallel_reduce。 
 3 模板类 atomic 中提供了无锁(Lock-free或者mutex-free)并发编程支持。

方案4 无锁数据结构支持库Concurrent Data Structures (libcds). 
地址 http://sourceforge.net/projects/libcds/
下载以后里面直接有从VC2008到VC2013的编译环境,依赖于boost库

方案5 Boost 使用boost.lockfree

boost.lockfree实现了三种无锁数据结构:


1 boost::lockfree::queue
2 boost::lockfree::stack
3 boost::lockfree::spsc_queue

生产者-消费者
下面的代码实现的是
实现了一个多写生成,多消费 队列。
产生整数,并被4个线程消费
 

 
  1. #include <boost/thread/thread.hpp>

  2. #include <boost/lockfree/queue.hpp>

  3. #include <iostream>

  4.  
  5.  
  6. #include <boost/atomic.hpp>

  7.  
  8.  
  9. boost::atomic_int producer_count(0);

  10. boost::atomic_int consumer_count(0);

  11.  
  12.  
  13. boost::lockfree::queue<int> queue(128);

  14.  
  15.  
  16. const int iterations = 10000000;

  17. const int producer_thread_count = 4;

  18. const int consumer_thread_count = 4;

  19.  
  20.  
  21. void producer(void)

  22. {

  23. for (int i = 0; i != iterations; ++i) {

  24. int value = ++producer_count;

  25. while (!queue.push(value))

  26. ;

  27. }

  28. }

  29.  
  30.  
  31. boost::atomic<bool> done (false);

  32. void consumer(void)

  33. {

  34. int value;

  35. while (!done) {

  36. while (queue.pop(value))

  37. ++consumer_count;

  38. }

  39.  
  40.  
  41. while (queue.pop(value))

  42. ++consumer_count;

  43. }

  44.  
  45.  
  46. int main(int argc, char* argv[])

  47. {

  48. using namespace std;

  49. cout << "boost::lockfree::queue is ";

  50. if (!queue.is_lock_free())

  51. cout << "not ";

  52. cout << "lockfree" << endl;

  53.  
  54.  
  55. boost::thread_group producer_threads, consumer_threads;

  56.  
  57.  
  58. for (int i = 0; i != producer_thread_count; ++i)

  59. producer_threads.create_thread(producer);

  60.  
  61.  
  62. for (int i = 0; i != consumer_thread_count; ++i)

  63. consumer_threads.create_thread(consumer);

  64.  
  65.  
  66. producer_threads.join_all();

  67. done = true;

  68.  
  69.  
  70. consumer_threads.join_all();

  71.  
  72.  
  73. cout << "produced " << producer_count << " objects." << endl;

  74. cout << "consumed " << consumer_count << " objects." << endl;

  75. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值