版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/okiwilldoit/article/details/50970408

在开发接收转发agent时,采用了多线程的生产者-消费者模式,用了加互斥锁的方式来实现线程同步。互斥锁会阻塞线程,所以压测时,效率并不高。所以想起用无锁队列来实现,性能确实提升了。

首先介绍下lock-free和wait-free的区别:

阻塞算法可能会出现整个系统都挂起的情况(占有锁的线程被中断,无法释放所,那么所有试图争用这个锁的线程会被挂起),系统中的所有线程全部饿死。

无锁算法可以保证系统中至少有一个线程处于工作状态,但是还是可能有线程永远抢不到资源而被饿死。

无等待算法保证系统中的所有线程都能处于工作状态,没有线程会被饿死,只要时间够,所有线程都能结束。相比于无锁算法,无等待算法有更强的保证。

一. 用互斥锁实现单生产者-单消费者

#include <string>
#include <sstream>
#include <list>
#include <pthread.h>
#include <iostream>
#include <time.h> using namespace std; int producer_count = 0;
int consumer_count = 0; list<string> product;
list<string> consumer_list;
pthread_mutex_t mutex; const int iterations = 10000; //是否生产完毕标志
bool done = false; void* producer(void* args)
{
for (int i = 0; i != iterations; ++i) {
pthread_mutex_lock(&mutex);
int value = ++producer_count;
stringstream ss;
ss<<value;
product.push_back(ss.str());
//cout<<"list push:"<<ss.str()<<endl;
pthread_mutex_unlock(&mutex);
}
return 0;
} //消费函数
void* consumer(void* args)
{
//当没有生产完毕,则边消费边生产
while (!done) {
pthread_mutex_lock(&mutex);
if(!product.empty()){
consumer_list.splice(consumer_list.end(), product);
pthread_mutex_unlock(&mutex);
while(!consumer_list.empty()){
string value = consumer_list.front();
consumer_list.pop_front();
//cout<<"list pop:"<<value<<endl;
++consumer_count;
}
}else{
pthread_mutex_unlock(&mutex);
}
}
//如果生产完毕,则消费
while(!consumer_list.empty()){
string value = consumer_list.front();
consumer_list.pop_front();
//cout<<"list pop:"<<value<<endl;
++consumer_count;
}
return 0;
} int main(int argc, char* argv[])
{
struct timespec time_start={0, 0},time_end={0, 0};
clock_gettime(CLOCK_REALTIME, &time_start); pthread_t producer_tid;
pthread_t consumer_tid; pthread_mutex_init (&mutex,NULL);
pthread_create(&producer_tid, NULL, producer, NULL);
pthread_create(&consumer_tid, NULL, consumer, NULL); //等待生产者生产完毕
pthread_join(producer_tid, NULL);
//可以消费标志
done = true; //主线程不等生产线程完毕就设置done标记
cout << "producer done" << endl; //输出以观察主线程和各子线程的执行顺序 //等待消费者结束
pthread_join(consumer_tid, NULL);
clock_gettime(CLOCK_REALTIME, &time_end); long cost = (time_end.tv_sec-time_start.tv_sec)/1000000 + (time_end.tv_nsec-time_start.tv_nsec)/1000; cout<<"===========cost time:"<<cost<<"us==========="<<endl; cout << "produced " << producer_count << " objects." << endl;
cout << "consumed " << consumer_count << " objects." << endl;
}

生产消费10000个string类型的数据,耗时:58185us

二. Boost库的无锁队列

boost.lockfree实现了三种无锁数据结构:
boost::lockfree::queue
alock-free multi-produced/multi-consumer queue
一个无锁的多生产者/多消费者队列,注意,这个queue不支持string类型,支持的数据类型要求:
- T must have a copy constructor
- T must have a trivial assignment operator
- T must have a trivial destructor

boost::lockfree::stack
alock-free multi-produced/multi-consumer stack
一个无锁的多生产者/多消费者栈,支持的数据类型要求:
- T must have a copy constructor

boost::lockfree::spsc_queue
await-free single-producer/single-consumer queue (commonly known as ringbuffer)
一个无等待的单生产者/单消费者队列(通常被称为环形缓冲区),支持的数据类型要求:
- T must have a default constructor
- T must be copyable

详细资料可以看官方文档:http://www.boost.org/doc/libs/1_55_0/doc/html/lockfree.html

三. Queue示例

这里实现的还是单生产者-单消费者。

#include <pthread.h>
#include <boost/lockfree/queue.hpp>
#include <iostream>
#include <time.h>
#include <boost/atomic.hpp> using namespace std; //生产数量
boost::atomic_int producer_count(0);
//消费数量
boost::atomic_int consumer_count(0);
//队列
boost::lockfree::queue<int> queue(512); //迭代次数
const int iterations = 10000; //生产函数
void* producer(void* args)
{
for (int i = 0; i != iterations; ++i) {
int value = ++producer_count;
//原子计数————多线程不存在计数不上的情况
//若没有进入队列,则重复推送
while(!queue.push(value));
//cout<<"queue push:"<<value<<endl;
}
return 0;
} //是否生产完毕标志
boost::atomic<bool> done (false); //消费函数
void* consumer(void* args)
{
int value;
//当没有生产完毕,则边消费边生产
while (!done) {
//只要能弹出元素,就消费
while (queue.pop(value)) {
//cout<<"queue pop:"<<value<<endl;
++consumer_count;
}
}
//如果生产完毕,则消费
while (queue.pop(value)){
//cout<<"queue pop:"<<value<<endl;
++consumer_count;
}
return 0;
} int main(int argc, char* argv[])
{
cout << "boost::lockfree::queue is ";
if (!queue.is_lock_free())
cout << "not ";
cout << "lockfree" << endl; struct timespec time_start={0, 0},time_end={0, 0};
clock_gettime(CLOCK_REALTIME, &time_start); pthread_t producer_tid;
pthread_t consumer_tid; pthread_create(&producer_tid, NULL, producer, NULL);
pthread_create(&consumer_tid, NULL, consumer, NULL); //等待生产者生产完毕
pthread_join(producer_tid, NULL);
//可以消费标志
done = true; //主线程不等生产线程完毕就设置done标记
cout << "producer done" << endl; //输出以观察主线程和各子线程的执行顺序 //等待消费者结束
pthread_join(consumer_tid, NULL);
clock_gettime(CLOCK_REALTIME, &time_end); long cost = (time_end.tv_sec-time_start.tv_sec)/1000000 + (time_end.tv_nsec-time_start.tv_nsec)/1000; cout<<"===========cost time:"<<cost<<"us==========="<<endl; //输出生产和消费数量
cout << "produced " << producer_count << " objects." << endl;
cout << "consumed " << consumer_count << " objects." << endl; return 0;
}

生产消费10000个int类型的数据,耗时:3963us
stack与queue类似,只不过是先进后出。

四. Waitfree Single-Producer/Single-Consumer Queue无等待单生产者/单消费者队列

#include <pthread.h>
#include <iostream>
#include <time.h>
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/atomic.hpp> using namespace std; int producer_count = 0;
boost::atomic_int consumer_count (0); boost::lockfree::spsc_queue<int, boost::lockfree::capacity<1024> > spsc_queue; const int iterations = 10000; void* producer(void* args)
{
for (int i = 0; i != iterations; ++i) {
int value = ++producer_count;
while(!spsc_queue.push(value));
//cout<<"queue push:"<<value<<endl;
}
return 0;
} //是否生产完毕标志
boost::atomic<bool> done (false); //消费函数
void* consumer(void* args)
{
int value;
//当没有生产完毕,则边消费边生产
while (!done) {
//只要能弹出元素,就消费
while (spsc_queue.pop(value)) {
//cout<<"queue pop:"<<value<<endl;
++consumer_count;
}
}
//如果生产完毕,则消费
while (spsc_queue.pop(value)){
//cout<<"queue pop:"<<value<<endl;
++consumer_count;
}
return 0;
} int main(int argc, char* argv[])
{
using namespace std;
cout << "boost::lockfree::queue is ";
if (!spsc_queue.is_lock_free())
cout << "not ";
cout << "lockfree" << endl; struct timespec time_start={0, 0},time_end={0, 0};
clock_gettime(CLOCK_REALTIME, &time_start); pthread_t producer_tid;
pthread_t consumer_tid; pthread_create(&producer_tid, NULL, producer, NULL);
pthread_create(&consumer_tid, NULL, consumer, NULL); //等待生产者生产完毕
pthread_join(producer_tid, NULL);
//可以消费标志
done = true; //主线程不等生产线程完毕就设置done标记
cout << "producer done" << endl; //输出以观察主线程和各子线程的执行顺序 //等待消费者结束
pthread_join(consumer_tid, NULL);
clock_gettime(CLOCK_REALTIME, &time_end); long cost = (time_end.tv_sec-time_start.tv_sec)/1000000 + (time_end.tv_nsec-time_start.tv_nsec)/1000; cout<<"===========cost time:"<<cost<<"us==========="<<endl; cout << "produced " << producer_count << " objects." << endl;
cout << "consumed " << consumer_count << " objects." << endl;
}

生产消费10000个int类型的数据,耗时:1832us
如果把int改为string类型,耗时:28788us

五.性能对比


从上面可以看出在单生产者-单消费者模式下,spsc_queue比queue性能好,无锁队列比互斥锁的方式性能也要好。

Boost无锁队列的更多相关文章

  1. boost 无锁队列

    一哥们翻译的boost的无锁队列的官方文档 原文地址:http://blog.csdn.net/great3779/article/details/8765103 Boost_1_53_0终于迎来了久 ...

  2. 基于Boost无锁队列实现的内存池

  3. 无锁队列以及ABA问题

    队列是我们非常常用的数据结构,用来提供数据的写入和读取功能,而且通常在不同线程之间作为数据通信的桥梁.不过在将无锁队列的算法之前,需要先了解一下CAS(compare and swap)的原理.由于多 ...

  4. HashMap的原理与实 无锁队列的实现Java HashMap的死循环 red black tree

    http://www.cnblogs.com/fornever/archive/2011/12/02/2270692.html https://zh.wikipedia.org/wiki/%E7%BA ...

  5. zeromq源码分析笔记之无锁队列ypipe_t(3)

    在上一篇中说到了mailbox_t的底层实际上使用了管道ypipe_t来存储命令.而ypipe_t实质上是一个无锁队列,其底层使用了yqueue_t队列,ypipe_t是对yueue_t的再包装,所以 ...

  6. 一个可无限伸缩且无ABA问题的无锁队列

    关于无锁队列,详细的介绍请参考陈硕先生的<无锁队列的实现>一文.然进一步,如何实现一个不限node数目即能够无限伸缩的无锁队列,即是本文的要旨. 无锁队列有两种实现形式,分别是数组与链表. ...

  7. 无锁队列--基于linuxkfifo实现

    一直想写一个无锁队列,为了提高项目的背景效率. 有机会看到linux核心kfifo.h 原则. 所以这个实现自己仿照,眼下linux我们应该能够提供外部接口. #ifndef _NO_LOCK_QUE ...

  8. CAS简介和无锁队列的实现

    Q:CAS的实现 A:gcc提供了两个函数 bool __sync_bool_compare_and_swap (type *ptr, type oldval, type newval, ...)// ...

  9. Go语言无锁队列组件的实现 (chan/interface/select)

    1. 背景 go代码中要实现异步很简单,go funcName(). 但是进程需要控制协程数量在合理范围内,对应大批量任务可以使用"协程池 + 无锁队列"实现. 2. golang ...

随机推荐

  1. HTML5之客户端存储(Storage)

    关于客户端存储技术 storage 一.关于客户端(浏览器)存储技术 浏览器的存储技术第一个能想到的应该就是cookie,关于cookie本身出现的初衷是为了解决客户端识别,可存储信息量小(4k左右) ...

  2. location(重定向,跳转到其他网页)

    <?php header('Location : https://www.baidu.com'); 这里是在响应头中添加一个 location 的头信息 客户端浏览器在接收到这个头信息过后会自动 ...

  3. shell运行下的写日志

    tee 重定向输出到多个文件   在执行Linux命令时,我们既想把输出保存到文件中,又想在屏幕上看到输出内容,就可以使用tee命令 要注意的是:在使用管道线时,前一个命令的标准错误输出不会被tee读 ...

  4. 第十五章、Python多线程之信号量和GIL

    目录 第十五章.Python多线程之信号量和GIL 1. 信号量(Semaphore) 2. GIL 说明: 第十五章.Python多线程之信号量和GIL 1. 信号量(Semaphore) 信号量用 ...

  5. U盘加载速度慢的解决方法

    在日常的生活和工作中,我们经常用U盘存储一些文件和程序.然而,一些朋友发现U盘有时候在使用过程中的识别加载速度非常缓慢.是U盘出故障了吗?其实不尽然,下面就为大家分享一下如何快速解决U盘加载缓慢的方法 ...

  6. Use pkgsrc on ARM

    What is this page? This page describes how to use pkgsrc on ARM architecture with EABI support. I bo ...

  7. Oracle【三表的联合查询】

    ,'北京','彰显大气'); ,'上海','繁华都市'); ,'广州','凸显舒适'); ,'深圳','年轻气氛'); ,'北上广深','不相信眼泪'); commit; ; ; ; ; ; 员工信息 ...

  8. err:LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLE

    err:LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLE err:LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLE err:LIBUSB_S ...

  9. LeetCode01 - 两数之和(Java 实现)

    LeetCode01 - 两数之和(Java 实现) 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum 题目描述 给定一个整数数组 ...

  10. MyBatis Generator 移除字段前缀

    在table标签内添加 <columnRenamingRule searchString="wrc_" replaceString=""/> < ...