基于锁实现线程安全队列和栈容器

简介

本文介绍如何通过互斥锁和条件变量等并发机制实现线程安全的队列和栈容器。

线程安全的栈

实现一个线程安全的栈,我们能想到的是基于锁控制push和pop操作,比如下面的逻辑

  1. #include <exception>
  2. #include <mutex>
  3. #include <stack>
  4. #include <condition_variable>
  5. struct empty_stack : std::exception
  6. {
  7. const char* what() const throw();
  8. };
  9. template<typename T>
  10. class threadsafe_stack
  11. {
  12. private:
  13. std::stack<T> data;
  14. mutable std::mutex m;
  15. public:
  16. threadsafe_stack() {}
  17. threadsafe_stack(const threadsafe_stack& other)
  18. {
  19. std::lock_guard<std::mutex> lock(other.m);
  20. data = other.data;
  21. }
  22. threadsafe_stack& operator=(const threadsafe_stack&) = delete;
  23. void push(T new_value)
  24. {
  25. std::lock_guard<std::mutex> lock(m);
  26. data.push(std::move(new_value)); // ⇽-- - 1
  27. }
  28. std::shared_ptr<T> pop()
  29. {
  30. std::lock_guard<std::mutex> lock(m);
  31. if (data.empty()) throw empty_stack(); // ⇽-- - 2
  32. std::shared_ptr<T> const res(
  33. std::make_shared<T>(std::move(data.top()))); // ⇽-- - 3
  34. data.pop(); // ⇽-- - 4
  35. return res;
  36. }
  37. void pop(T& value)
  38. {
  39. std::lock_guard<std::mutex> lock(m);
  40. if (data.empty()) throw empty_stack();
  41. value = std::move(data.top()); // ⇽-- - 5
  42. data.pop(); // ⇽-- - 6
  43. }
  44. bool empty() const
  45. {
  46. std::lock_guard<std::mutex> lock(m);
  47. return data.empty();
  48. }
  49. };

我们实现了push操作和pop操作

  1. push操作里加锁,然后将数据通过std::move的方式移动放入stack中。我们思考如果1处因为机器内存不足push导致异常,此种情况并不会对栈已有的数据产生危险。

但是vector容器大家要考虑,因为vector存在内存不足时将数据拷贝转移到新空间的过程。那么对于vector这种动态扩容的容器该如何保证容器内数据在移动过程中出现了异常仍能不丢失呢?

我想到的一个方式就是管理vector的capacity,每次push的时候要判断一下vector的size和capacity是否相等,如果相等则手动扩容并将数据转移到新的vector,再释放旧有的vector。

但是同样会存在一个问题就是会造成内存溢出,因为vector的capacity会随着数据增加而增加,当vector中没有数据的时候capacity仍然很大。这种方式也可以通过swap的方式将当前大容量的vector和一个空的vector做交换,快速清空内存。这些操作和思路需结合实际开发情况而定。

  1. pop提供了两个版本,一个是返回智能指针一个是返回bool类型,这两种我们分析,比如3处和4处也很可能因为内存不足导致构造智能指针失败,或者5处赋值失败,这种情况下抛出异常并不会影响栈内数据,因为程序没走到4和6处就抛出异常了。

  2. pop函数内部判断栈是否空,如果为空则抛出异常,这种情况我们不能接受,异常是用来处理和预判突发情况的,对于一个栈为空这种常见现象,仅需根据返回之后判断为空再做尝试或放弃出栈即可。

为了解决栈为空就抛出异常的问题,我们可以做如下优化

  1. template<typename T>
  2. class threadsafe_stack_waitable
  3. {
  4. private:
  5. std::stack<T> data;
  6. mutable std::mutex m;
  7. std::condition_variable cv;
  8. public:
  9. threadsafe_stack_waitable() {}
  10. threadsafe_stack_waitable(const threadsafe_stack_waitable& other)
  11. {
  12. std::lock_guard<std::mutex> lock(other.m);
  13. data = other.data;
  14. }
  15. threadsafe_stack_waitable& operator=(const threadsafe_stack_waitable&) = delete;
  16. void push(T new_value)
  17. {
  18. std::lock_guard<std::mutex> lock(m);
  19. data.push(std::move(new_value)); // ⇽-- - 1
  20. cv.notify_one();
  21. }
  22. std::shared_ptr<T> wait_and_pop()
  23. {
  24. std::unique_lock<std::mutex> lock(m);
  25. cv.wait(lock, [this]()
  26. {
  27. if(data.empty())
  28. {
  29. return false;
  30. }
  31. return true;
  32. }); // ⇽-- - 2
  33. std::shared_ptr<T> const res(
  34. std::make_shared<T>(std::move(data.top()))); // ⇽-- - 3
  35. data.pop(); // ⇽-- - 4
  36. return res;
  37. }
  38. void wait_and_pop(T& value)
  39. {
  40. std::unique_lock<std::mutex> lock(m);
  41. cv.wait(lock, [this]()
  42. {
  43. if (data.empty())
  44. {
  45. return false;
  46. }
  47. return true;
  48. });
  49. value = std::move(data.top()); // ⇽-- - 5
  50. data.pop(); // ⇽-- - 6
  51. }
  52. bool empty() const
  53. {
  54. std::lock_guard<std::mutex> lock(m);
  55. return data.empty();
  56. }
  57. bool try_pop(T& value)
  58. {
  59. std::lock_guard<std::mutex> lock(m);
  60. if(data.empty())
  61. {
  62. return false;
  63. }
  64. value = std::move(data.top());
  65. data.pop();
  66. return true;
  67. }
  68. std::shared_ptr<T> try_pop()
  69. {
  70. std::lock_guard<std::mutex> lock(m);
  71. if(data.empty())
  72. {
  73. return std::shared_ptr<T>();
  74. }
  75. std::shared_ptr<T> res(std::make_shared<T>(std::move(data.top())));
  76. data.pop();
  77. return res;
  78. }
  79. };

我们将pop优化为四个版本,四个版本又可以分为两个大类,两个大类分别为try_pop版本和wait_and_pop版本。

try_pop版本不阻塞等待队列有数据才返回,而是直接返回,try_pop又有两个版本,分别返回bool值和指针值。如果队列为空返回false或者空指针。

wait_and_pop版本阻塞等待队列有数据才返回,同样有两个版本,分别返回bool值和指针值。

但是上面的代码我们分析,假设此时栈为空,有一个线程A从队列中消费数据,调用wait_and_pop挂起, 此时另一个线程B向栈中放入数据调用push操作,notify一个线程消费队列中的数据。

此时A从wait_and_pop唤醒,但是在执行3或者5处时,因为内存不足引发了异常,我们之前分析过,即使引发异常也不会影响到栈内数据,所以对于栈的数据来说是安全的,但是线程A异常后,其他线程无法从队列中消费数据,除非线程B再执行一次push。因为我们采用的是notify_one的方式,所以仅有一个线程被激活,如果被激活的线程异常了,就不能保证该数据被其他线程消费了,解决这个问题,可以采用几个方案。

  1. wai_and_pop失败的线程修复后再次取一次数据。
  2. notify_one改为notify_all,这样能保证通知所有线程。但是notify_all将导致所有线程竞争,并不可取。
  3. 我们可以通过栈存储智能指针的方式进行,因为智能指针在赋值的时候不会引发异常。

稍后我们提供的线程安全队列的版本使用的就是第三种优化。

线程安全队列

队列和栈最大的不同就是队列为先入先出,有了线程安全的栈的开发思路,我们很快实现一个支持线程安全的队列

  1. #include <mutex>
  2. #include <queue>
  3. template<typename T>
  4. class threadsafe_queue
  5. {
  6. private:
  7. mutable std::mutex mut;
  8. std::queue<T> data_queue;
  9. std::condition_variable data_cond;
  10. public:
  11. threadsafe_queue()
  12. {}
  13. void push(T new_value)
  14. {
  15. std::lock_guard<std::mutex> lk(mut);
  16. data_queue.push(std::move(new_value));
  17. data_cond.notify_one(); //⇽-- - ①
  18. }
  19. void wait_and_pop(T& value) //⇽-- - ②
  20. {
  21. std::unique_lock<std::mutex> lk(mut);
  22. data_cond.wait(lk, [this] {return !data_queue.empty(); });
  23. value = std::move(data_queue.front());
  24. data_queue.pop();
  25. }
  26. std::shared_ptr<T> wait_and_pop() // ⇽-- - ③
  27. {
  28. std::unique_lock<std::mutex> lk(mut);
  29. data_cond.wait(lk, [this] {return !data_queue.empty(); }); // ⇽-- - ④
  30. std::shared_ptr<T> res(
  31. std::make_shared<T>(std::move(data_queue.front())));
  32. data_queue.pop();
  33. return res;
  34. }
  35. bool try_pop(T& value)
  36. {
  37. std::lock_guard<std::mutex> lk(mut);
  38. if (data_queue.empty())
  39. return false;
  40. value = std::move(data_queue.front());
  41. data_queue.pop();
  42. return true;
  43. }
  44. std::shared_ptr<T> try_pop()
  45. {
  46. std::lock_guard<std::mutex> lk(mut);
  47. if (data_queue.empty())
  48. return std::shared_ptr<T>(); //⇽-- - ⑤
  49. std::shared_ptr<T> res(
  50. std::make_shared<T>(std::move(data_queue.front())));
  51. data_queue.pop();
  52. return res;
  53. }
  54. bool empty() const
  55. {
  56. std::lock_guard<std::mutex> lk(mut);
  57. return data_queue.empty();
  58. }
  59. };

关于异常情况的分析和栈一样,上面的队列版本不存在异常导致数据丢失的问题。但是同样面临线程执行wait_and_pop时如果出现了异常,导致数据被滞留在队列中,其他线程也无法被唤醒的情况。

为了解决这种情况,我们前文提到了采用智能指针的方式,重新实现一下线程安全队列

  1. template<typename T>
  2. class threadsafe_queue_ptr
  3. {
  4. private:
  5. mutable std::mutex mut;
  6. std::queue<std::shared_ptr<T>> data_queue;
  7. std::condition_variable data_cond;
  8. public:
  9. threadsafe_queue_ptr()
  10. {}
  11. void wait_and_pop(T& value)
  12. {
  13. std::unique_lock<std::mutex> lk(mut);
  14. data_cond.wait(lk, [this] {return !data_queue.empty(); });
  15. value = std::move(*data_queue.front()); //⇽-- - 1
  16. data_queue.pop();
  17. }
  18. bool try_pop(T& value)
  19. {
  20. std::lock_guard<std::mutex> lk(mut);
  21. if (data_queue.empty())
  22. return false;
  23. value = std::move(*data_queue.front()); // ⇽-- - 2
  24. data_queue.pop();
  25. return true;
  26. }
  27. std::shared_ptr<T> wait_and_pop()
  28. {
  29. std::unique_lock<std::mutex> lk(mut);
  30. data_cond.wait(lk, [this] {return !data_queue.empty(); });
  31. std::shared_ptr<T> res = data_queue.front(); // ⇽-- - 3
  32. data_queue.pop();
  33. return res;
  34. }
  35. std::shared_ptr<T> try_pop()
  36. {
  37. std::lock_guard<std::mutex> lk(mut);
  38. if (data_queue.empty())
  39. return std::shared_ptr<T>();
  40. std::shared_ptr<T> res = data_queue.front(); // ⇽-- - 4
  41. data_queue.pop();
  42. return res;
  43. }
  44. void push(T new_value)
  45. {
  46. std::shared_ptr<T> data(
  47. std::make_shared<T>(std::move(new_value))); // ⇽-- - 5
  48. std::lock_guard<std::mutex> lk(mut);
  49. data_queue.push(data);
  50. data_cond.notify_one();
  51. }
  52. bool empty() const
  53. {
  54. std::lock_guard<std::mutex> lk(mut);
  55. return data_queue.empty();
  56. }
  57. };

在5处,我们push数据时需要先构造智能指针,如果构造的过程失败了也就不会push到队列中,不会污染队列中的数据。

2,3处和4,5处我们仅仅时将智能指针取出来赋值给一个新的智能指针并返回。关于智能指针的赋值不会引发异常这一点在C++并发编程中提及,这一点我觉得有些存疑,我觉得书中表述的意思应该是指针在64位机器占用8个字节,所有智能指针共享引用计数所以在复制时仅为8字节开销,降低了内存消耗。

所以推荐大家存储数据放入容器中时尽量用智能指针,这样能保证复制和移动过程中开销较小,也可以实现一定意义的数据共享。

但是我们分析上面的代码,队列push和pop时采用的是一个mutex,导致push和pop等操作串行化,我们要考虑的是优化锁的精度,提高并发,那有什么办法吗?

我们分析,队列和栈最本质的区别是队列是首尾操作。我们可以考虑将push和pop操作分化为分别对尾和对首部的操作。对首和尾分别用不同的互斥量管理就可以实现真正意义的并发了。

我们引入虚位节点的概念,表示一个空的节点,没有数据,是一个无效的节点,初始情况下,队列为空,head和tail节点都指向这个虚位节点。

https://cdn.llfc.club/1700371510300.jpg

当我们push一个数据,比如为MyClass类型的数据后,tail向后移动一个位置,并且仍旧指向这个虚位节点。

如下图

https://cdn.llfc.club/1700371711311.jpg

接下来我们实现这个版本的并发安全队列

  1. template<typename T>
  2. class threadsafe_queue_ht
  3. {
  4. private:
  5. struct node
  6. {
  7. std::shared_ptr<T> data;
  8. std::unique_ptr<node> next;
  9. };
  10. std::mutex head_mutex;
  11. std::unique_ptr<node> head;
  12. std::mutex tail_mutex;
  13. node* tail;
  14. std::condition_variable data_cond;
  15. node* get_tail()
  16. {
  17. std::lock_guard<std::mutex> tail_lock(tail_mutex);
  18. return tail;
  19. }
  20. std::unique_ptr<node> pop_head()
  21. {
  22. std::unique_ptr<node> old_head = std::move(head);
  23. head = std::move(old_head->next);
  24. return old_head;
  25. }
  26. std::unique_lock<std::mutex> wait_for_data()
  27. {
  28. std::unique_lock<std::mutex> head_lock(head_mutex);
  29. data_cond.wait(head_lock,[&] {return head.get() != get_tail(); }); //5
  30. return std::move(head_lock);
  31. }
  32. std::unique_ptr<node> wait_pop_head()
  33. {
  34. std::unique_lock<std::mutex> head_lock(wait_for_data());
  35. return pop_head();
  36. }
  37. std::unique_ptr<node> wait_pop_head(T& value)
  38. {
  39. std::unique_lock<std::mutex> head_lock(wait_for_data());
  40. value = std::move(*head->data);
  41. return pop_head();
  42. }
  43. std::unique_ptr<node> try_pop_head()
  44. {
  45. std::lock_guard<std::mutex> head_lock(head_mutex);
  46. if (head.get() == get_tail())
  47. {
  48. return std::unique_ptr<node>();
  49. }
  50. return pop_head();
  51. }
  52. std::unique_ptr<node> try_pop_head(T& value)
  53. {
  54. std::lock_guard<std::mutex> head_lock(head_mutex);
  55. if (head.get() == get_tail())
  56. {
  57. return std::unique_ptr<node>();
  58. }
  59. value = std::move(*head->data);
  60. return pop_head();
  61. }
  62. public:
  63. threadsafe_queue_ht() : // ⇽-- - 1
  64. head(new node), tail(head.get())
  65. {}
  66. threadsafe_queue_ht(const threadsafe_queue_ht& other) = delete;
  67. threadsafe_queue_ht& operator=(const threadsafe_queue_ht& other) = delete;
  68. std::shared_ptr<T> wait_and_pop() // <------3
  69. {
  70. std::unique_ptr<node> const old_head = wait_pop_head();
  71. return old_head->data;
  72. }
  73. void wait_and_pop(T& value) // <------4
  74. {
  75. std::unique_ptr<node> const old_head = wait_pop_head(value);
  76. }
  77. std::shared_ptr<T> try_pop()
  78. {
  79. std::unique_ptr<node> old_head = try_pop_head();
  80. return old_head ? old_head->data : std::shared_ptr<T>();
  81. }
  82. bool try_pop(T& value)
  83. {
  84. std::unique_ptr<node> const old_head = try_pop_head(value);
  85. return old_head;
  86. }
  87. bool empty()
  88. {
  89. std::lock_guard<std::mutex> head_lock(head_mutex);
  90. return (head.get() == get_tail());
  91. }
  92. void push(T new_value) //<------2
  93. {
  94. std::shared_ptr<T> new_data(
  95. std::make_shared<T>(std::move(new_value)));
  96. std::unique_ptr<node> p(new node);
  97. node* const new_tail = p.get();
  98. std::lock_guard<std::mutex> tail_lock(tail_mutex);
  99. tail->data = new_data;
  100. tail->next = std::move(p);
  101. tail = new_tail;
  102. data_cond.notify_one();
  103. }
  104. };

node为节点类型,包含data和next两个成员。 data为智能指针类型存储T类型的数据。next为指向下一个节点的智能指针,以此形成链表。

上述代码我们的head是一个node类型的智能指针。而tail为node类型的普通指针,读者也可以用智能指针。

在1处构造函数那里,我们将head和tail初始指向的位置设置为虚位节点。

在2 处我们push数据的时候先构造T类型的智能指针存储数据new_data,然后我们构造了一个新的智能指针p, p取出裸指针就是新的虚位节点new_tail,我们将new_data赋值给现在的尾节点,并且让尾节点的next指针指向p, 然后将tail更新为我们新的虚位节点。

3,4处都是wait_and_pop的不同版本,内部调用了wait_pop_head,wait_pop_head内部先调用wait_for_data判断队列是否为空,这里判断是否为空主要是判断head是否指向虚位节点。如果不为空则返回unique_lock,我们显示的调用了move操作,返回unique_lock仍保留对互斥量的锁住状态。

回到wait_pop_head中,接下来执行pop_head将数据pop出来。

值得注意的是get_tail()返回tail节点,那么我们思考如果此时有多个线程push数据,tail节点已经变化了,我们此时在5处的判断可能是基于push之前的tail信息,但是不影响逻辑,因为如果head和tail相等则线程挂起,等待通知,如果不等则继续执行,push操作只会将tail向后移动不会导致逻辑问题。

pop_head中我们将head节点移动给一个old_head变量,然后将old_head的next节点更新为新的head。这里我觉得可以简化写为head=head->next.

测试结果详见源码

总结

本文介绍了线程安全情况下栈和队列的实现方式

源码链接:

https://gitee.com/secondtonone1/boostasio-learn/tree/master/concurrent/day14-ThreadSafeContainer

视频链接

https://space.bilibili.com/271469206/channel/collectiondetail?sid=1623290

热门评论

热门文章

  1. C++ 类的继承封装和多态

    喜欢(588) 浏览(3252)
  2. Linux环境搭建和编码

    喜欢(594) 浏览(7072)
  3. windows环境搭建和vscode配置

    喜欢(587) 浏览(1870)
  4. slice介绍和使用

    喜欢(521) 浏览(1945)
  5. 解密定时器的实现细节

    喜欢(566) 浏览(2327)

最新评论

  1. asio多线程模型IOServicePool Lion:线程池一定要继承单例模式吗
  2. 泛型算法的定制操作 secondtonone1:lambda和bind是C11新增的利器,善于利用这两个机制可以极大地提升编程安全性和效率。
  3. 类和对象 陈宇航:支持!!!!
  4. C++ 虚函数表原理和类成员内存分布 WangQi888888:class Test{ int m; int b; }中b成员是int,为什么在内存中只占了1个字节。不应该是4个字节吗?是不是int应该改为char。这样的话就会符合图上说明的情况
  5. 解决博客回复区被脚本注入的问题 secondtonone1:走到现在我忽然明白一个道理,无论工作也好生活也罢,最重要的是开心,即使一份安稳的工作不能给我带来事业上的积累也要合理的舍弃,所以我还是想去做喜欢的方向。

个人公众号

个人微信