boost库中有一个boost::lockfree::queue类型的 队列,对于一般的需要队列的程序,其效率都算不错的了,下面使用一个用例来说明。

  程序是一个典型的生产者与消费者的关系,都可以使用多线程,其效率要比使用上层的互斥锁要快很多,因为它直接使用底层的原子操作来进行同步数据的。

  freedeque.h

  1. #pragma once#ifndef INCLUDED_UTILS_LFRINGQUEUE
  2. #define INCLUDED_UTILS_LFRINGQUEUE
  3.  
  4. #define _ENABLE_ATOMIC_ALIGNMENT_FIX
  5. #define ATOMIC_FLAG_INIT 0
  6.  
  7. #pragma once
  8.  
  9. #include <vector>
  10. #include <mutex>
  11. #include <thread>
  12. #include <atomic>
  13. #include <chrono>
  14. #include <cstring>
  15. #include <iostream>
  16.  
  17. // Lock free ring queue
  18.  
  19. template < typename _TyData, long _uiCount = >
  20. class lfringqueue
  21. {
  22. public:
  23. lfringqueue(long uiCount = _uiCount) : m_lTailIterator(), m_lHeadIterator(), m_uiCount(uiCount)
  24. {
  25. m_queue = new _TyData*[m_uiCount];
  26. memset(m_queue, , sizeof(_TyData*) * m_uiCount);
  27. }
  28.  
  29. ~lfringqueue()
  30. {
  31. if (m_queue)
  32. delete[] m_queue;
  33. }
  34.  
  35. bool enqueue(_TyData *pdata, unsigned int uiRetries = )
  36. {
  37. if (NULL == pdata)
  38. {
  39. // Null enqueues are not allowed
  40. return false;
  41. }
  42.  
  43. unsigned int uiCurrRetries = ;
  44. while (uiCurrRetries < uiRetries)
  45. {
  46. // Release fence in order to prevent memory reordering
  47. // of any read or write with following write
  48. std::atomic_thread_fence(std::memory_order_release);
  49.  
  50. long lHeadIterator = m_lHeadIterator;
  51.  
  52. if (NULL == m_queue[lHeadIterator])
  53. {
  54. long lHeadIteratorOrig = lHeadIterator;
  55.  
  56. ++lHeadIterator;
  57. if (lHeadIterator >= m_uiCount)
  58. lHeadIterator = ;
  59.  
  60. // Don't worry if this CAS fails. It only means some thread else has
  61. // already inserted an item and set it.
  62. if (std::atomic_compare_exchange_strong(&m_lHeadIterator, &lHeadIteratorOrig, lHeadIterator))
  63. {
  64. // void* are always atomic (you wont set a partial pointer).
  65. m_queue[lHeadIteratorOrig] = pdata;
  66.  
  67. if (m_lEventSet.test_and_set())
  68. {
  69. m_bHasItem.test_and_set();
  70. }
  71. return true;
  72. }
  73. }
  74. else
  75. {
  76. // The queue is full. Spin a few times to check to see if an item is popped off.
  77. ++uiCurrRetries;
  78. }
  79. }
  80. return false;
  81. }
  82.  
  83. bool dequeue(_TyData **ppdata)
  84. {
  85. if (!ppdata)
  86. {
  87. // Null dequeues are not allowed!
  88. return false;
  89. }
  90.  
  91. bool bDone = false;
  92. bool bCheckQueue = true;
  93.  
  94. while (!bDone)
  95. {
  96. // Acquire fence in order to prevent memory reordering
  97. // of any read or write with following read
  98. std::atomic_thread_fence(std::memory_order_acquire);
  99. //MemoryBarrier();
  100. long lTailIterator = m_lTailIterator;
  101. _TyData *pdata = m_queue[lTailIterator];
  102. //volatile _TyData *pdata = m_queue[lTailIterator];
  103. if (NULL != pdata)
  104. {
  105. bCheckQueue = true;
  106. long lTailIteratorOrig = lTailIterator;
  107.  
  108. ++lTailIterator;
  109. if (lTailIterator >= m_uiCount)
  110. lTailIterator = ;
  111.  
  112. //if ( lTailIteratorOrig == atomic_cas( (volatile long*)&m_lTailIterator, lTailIterator, lTailIteratorOrig ))
  113. if (std::atomic_compare_exchange_strong(&m_lTailIterator, &lTailIteratorOrig, lTailIterator))
  114. {
  115. // Sets of sizeof(void*) are always atomic (you wont set a partial pointer).
  116. m_queue[lTailIteratorOrig] = NULL;
  117.  
  118. // Gets of sizeof(void*) are always atomic (you wont get a partial pointer).
  119. *ppdata = (_TyData*)pdata;
  120.  
  121. return true;
  122. }
  123. }
  124. else
  125. {
  126. bDone = true;
  127. m_lEventSet.clear();
  128. }
  129. }
  130. *ppdata = NULL;
  131. return false;
  132. }
  133.  
  134. long countguess() const
  135. {
  136. long lCount = trycount();
  137.  
  138. if ( != lCount)
  139. return lCount;
  140.  
  141. // If the queue is full then the item right before the tail item will be valid. If it
  142. // is empty then the item should be set to NULL.
  143. long lLastInsert = m_lTailIterator - ;
  144. if (lLastInsert < )
  145. lLastInsert = m_uiCount - ;
  146.  
  147. _TyData *pdata = m_queue[lLastInsert];
  148. if (pdata != NULL)
  149. return m_uiCount;
  150.  
  151. return ;
  152. }
  153.  
  154. long getmaxsize() const
  155. {
  156. return m_uiCount;
  157. }
  158.  
  159. bool HasItem()
  160. {
  161. return m_bHasItem.test_and_set();
  162. }
  163.  
  164. void SetItemFlagBack()
  165. {
  166. m_bHasItem.clear();
  167. }
  168.  
  169. private:
  170. long trycount() const
  171. {
  172. long lHeadIterator = m_lHeadIterator;
  173. long lTailIterator = m_lTailIterator;
  174.  
  175. if (lTailIterator > lHeadIterator)
  176. return m_uiCount - lTailIterator + lHeadIterator;
  177.  
  178. // This has a bug where it returns 0 if the queue is full.
  179. return lHeadIterator - lTailIterator;
  180. }
  181.  
  182. private:
  183. std::atomic<long> m_lHeadIterator; // enqueue index
  184. std::atomic<long> m_lTailIterator; // dequeue index
  185. _TyData **m_queue; // array of pointers to the data
  186. long m_uiCount; // size of the array
  187. std::atomic_flag m_lEventSet = ATOMIC_FLAG_INIT; // a flag to use whether we should change the item flag
  188. std::atomic_flag m_bHasItem = ATOMIC_FLAG_INIT; // a flag to indicate whether there is an item enqueued
  189. };
  190.  
  191. #endif //INCLUDED_UTILS_LFRINGQUEUE

  

  1. /*
  2. * File: main.cpp
  3. * Author: Peng
  4. *
  5. * Created on February 22, 2014, 9:55 PM
  6. */
  7. #include <iostream>
  8. #include <string>
  9. #include "freedeque.h"
  10. #include <sstream>
  11. #include <boost/thread/thread.hpp>
  12. #include <boost/lockfree/queue.hpp>
  13. #include <boost/atomic.hpp>
  14. #include<boost/thread/lock_guard.hpp>
  15. #include<boost/thread/mutex.hpp>
  16. #include<boost/date_time/posix_time/posix_time.hpp>
  17.  
  18. const int NUM_ENQUEUE_THREAD = 5;
  19. const int NUM_DEQUEUE_THREAD = 10;
  20. const long NUM_ITEM = 50000;
  21. const long NUM_DATA = NUM_ENQUEUE_THREAD * NUM_ITEM;
  22.  
  23. class Data {
  24. public:
  25. Data(int i = 0) : m_iData(i)
  26. {
  27. std::stringstream ss;
  28. ss << i;
  29. m_szDataString = ss.str();
  30. }
  31.  
  32. bool operator< (const Data & aData) const
  33. {
  34. if (m_iData < aData.m_iData)
  35. return true;
  36. else
  37. return false;
  38. }
  39.  
  40. int& GetData()
  41. {
  42. return m_iData;
  43. }
  44. private:
  45. int m_iData;
  46. std::string m_szDataString;
  47. };
  48.  
  49. Data* g_arrData = new Data[NUM_DATA];
  50. boost::mutex mtx;
  51.  
  52. constexpr long size = 0.5 * NUM_DATA;
  53. lfringqueue < Data, 10000> LockFreeQueue;
  54. boost::lockfree::queue<Data*> BoostQueue(10000);
  55.  
  56. bool GenerateRandomNumber_FindPointerToTheNumber_EnQueue(int n)
  57. {
  58. for (long i = 0; i < NUM_ITEM; i++)
  59. {
  60. int x = i + NUM_ITEM * n;
  61. Data* pData = g_arrData + x;
  62. LockFreeQueue.enqueue(pData);
  63. }
  64. return true;
  65. }
  66.  
  67. void print(Data* pData) {
  68. if (!pData)
  69. return;
  70.  
  71. boost::lock_guard<boost::mutex> lock(mtx);
  72.  
  73. std::cout << pData->GetData() << std::endl;
  74.  
  75. }
  76.  
  77. bool Dequeue()
  78. {
  79. Data *pData = NULL;
  80.  
  81. while (true)
  82. {
  83. if (LockFreeQueue.dequeue(&pData) && pData)
  84. {
  85. print(pData);
  86. }
  87. else {
  88. boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(5));
  89. }
  90. }
  91.  
  92. return true;
  93. }
  94.  
  95. int main(int argc, char** argv)
  96. {
  97. for (int i = 0; i < NUM_DATA; ++i)
  98. {
  99. Data data(i);
  100. //DataArray[i] = data;
  101. *(g_arrData + i) = data;
  102. }
  103.  
  104. std::thread PublishThread[NUM_ENQUEUE_THREAD];
  105. std::thread ConsumerThread[NUM_DEQUEUE_THREAD];
  106. std::chrono::duration<double> elapsed_seconds;
  107.  
  108. for (int i = 0; i < NUM_ENQUEUE_THREAD; i++)
  109. {
  110. PublishThread[i] = std::thread(GenerateRandomNumber_FindPointerToTheNumber_EnQueue, i);
  111. }
  112.  
  113. for (int i = 0; i < NUM_DEQUEUE_THREAD; i++)
  114. {
  115. ConsumerThread[i] = std::thread{ Dequeue };
  116. }
  117.  
  118. for (int i = 0; i < NUM_DEQUEUE_THREAD; i++)
  119. {
  120. ConsumerThread[i].join();
  121. }
  122.  
  123. for (int i = 0; i < NUM_ENQUEUE_THREAD; i++)
  124. {
  125. PublishThread[i].join();
  126. }
  127.  
  128. delete[] g_arrData;
  129. return 0;
  130. }

  说明:模板文件是原作者写的,为了验证其正确性,后面的测试程序我改写了一下,最后测试程序是无法退出来的,这里只是测试,没有进一步完善了。

  在测试中发现deque应该是大小限制的,再增大data的数据程序会阻塞在某个地方没有进一步再查找原因了,以后有时候再做修改,对于一般的工程都够用了。

Boost lockfree deque 生产者与消费者多对多线程应用的更多相关文章

  1. 练习生产者与消费者-PYTHON多线程中的条件变量同步-Queue

    以前练习过,但好久不用,手生,概念也生了, 重温一下.. URL: http://www.cnblogs.com/holbrook/tag/%E5%A4%9A%E7%BA%BF%E7%A8%8B/ ~ ...

  2. [原创]如何编写多个阻塞队列连接下的多生产者多消费者的Python程序

    平常在写程序时,往往会遇到一个需求:在程序的多个阶段都会出现阻塞的可能,因此,这多个阶段就需要并发执行. Python的多线程有一个特点,就是不允许从外部结束一个运行中的线程,这给我们编写代码时带来了 ...

  3. 玩转Kafka的生产者——分区器与多线程

    上篇文章学习kafka的基本安装和基础概念,本文主要是学习kafka的常用API.其中包括生产者和消费者, 多线程生产者,多线程消费者,自定义分区等,当然还包括一些避坑指南. 首发于个人网站:链接地址 ...

  4. boost::lockfree::queue多线程读写实例

    最近的任务是写一个多线程的东西,就得接触多线程队列了,我反正是没学过分布式的,代码全凭感觉写出来的,不过运气好,代码能够work= = 话不多说,直接给代码吧,一个多消费者,多生产者的模式.假设我的任 ...

  5. 母鸡下蛋实例:多线程通信生产者和消费者wait/notify和condition/await/signal条件队列

    简介 多线程通信一直是高频面试考点,有些面试官可能要求现场手写生产者/消费者代码来考察多线程的功底,今天我们以实际生活中母鸡下蛋案例用代码剖析下实现过程.母鸡在鸡窝下蛋了,叫练从鸡窝里把鸡蛋拿出来这个 ...

  6. java多线程中的生产者与消费者之等待唤醒机制@Version1.0

    一.生产者消费者模式的学生类成员变量生产与消费demo,第一版1.等待唤醒:    Object类中提供了三个方法:    wait():等待    notify():唤醒单个线程    notify ...

  7. Java 多线程详解(四)------生产者和消费者

    Java 多线程详解(一)------概念的引入:http://www.cnblogs.com/ysocean/p/6882988.html Java 多线程详解(二)------如何创建进程和线程: ...

  8. JAVA基础再回首(二十五)——Lock锁的使用、死锁问题、多线程生产者和消费者、线程池、匿名内部类使用多线程、定时器、面试题

    JAVA基础再回首(二十五)--Lock锁的使用.死锁问题.多线程生产者和消费者.线程池.匿名内部类使用多线程.定时器.面试题 版权声明:转载必须注明本文转自程序猿杜鹏程的博客:http://blog ...

  9. JAVA之旅(十五)——多线程的生产者和消费者,停止线程,守护线程,线程的优先级,setPriority设置优先级,yield临时停止

    JAVA之旅(十五)--多线程的生产者和消费者,停止线程,守护线程,线程的优先级,setPriority设置优先级,yield临时停止 我们接着多线程讲 一.生产者和消费者 什么是生产者和消费者?我们 ...

随机推荐

  1. Javascript ——Navigator对象

    见 <Javascript 高级程序设计 第二版> P172 一.检测插件: 1.获取所有插件名称: 非IE浏览器:根据plugins数组, function getplugins() { ...

  2. JSP+Servlet 无数据库模拟登录过程

    程序目录结构: index.jsp: <%@ page language="java" contentType="text/html; charset=utf-8& ...

  3. Android LRUCache

    package android.util; import java.util.LinkedHashMap; import java.util.Map; /** * A cache that holds ...

  4. C# 把一个文件夹下所有文件删除

    public static void DelectDir(string srcPath){ try { DirectoryInfo dir = new DirectoryInfo(srcPath); ...

  5. 2018网络预选赛 徐州H 线段树+树状数组

    设读入的数组是a,树状数组用来维护a数组区间和sum,线段树用来维护一个另一个数组ssum的区间和,区间每个点a[i]*(n-i+1),那么l-r的答案是l-r的ssum-(n-r)*(sum[r]- ...

  6. SpringBoot04 日志框架之Logback

    1 日志框架选择 日志门面:SLF4J 日志实现:Logback 2 实现控制台的日志打印输出01 2.1 在需要实现日志信息打印的类中实例化Logger对象 坑01:springBoot项目默认使用 ...

  7. python pip ez_setup.py

    #!/usr/bin/env python """Bootstrap setuptools installation To use setuptools in your ...

  8. c语言学习笔记-变量、变量的命名、变量的赋值和变量的初始化

    在学习了简单的输入输出功能和了解了一些基本的运算符号之后我们可以试着做一个非常简单的计算器. 比如说想计算23+65 输入以下代码就可以了. printf("23+65=%d",2 ...

  9. JavaScript中的Array.prototype.slice.call()方法学习

    JavaScript中的Array.prototype.slice.call(arguments)能将有length属性的对象转换为数组(特别注意: 这个对象一定要有length属性). 但有一个例外 ...

  10. 并没有看起来那么简单leetcode Generate Parentheses

    问题解法参考 它给出了这个问题的探讨. 超时的代码: 这个当n等于7时,已经要很长时间出结果了.这个算法的复杂度是O(n^2). #include<iostream> #include&l ...