您的位置:首页 > 其它

boost线程库学习--(4)两个线程间使用队列进行通信

2014-02-24 20:25 736 查看
该程序使用boost线程库官方的demo修改而来,实现的功能很简单,主要是我学习两个线程使用队列进行通信使用。程序启动后创建了两个线程,一个用于每隔一秒向队列中加1个整数,另一个线程每隔1秒从队列主哦中取出一个整数。程序代码如下:

(1)、测试程序源代码:

/*
*File name:free_lock_queue.cpp
*Author:yingxianFei
*Date:2014-2-24
*Description:一个用于演示两个线程用队列进行数据交互的例子。一个线程用于每隔一秒向队列中添加数据,
一个线程用于每隔一秒从队列中读取数据,当添加完100个数据后等待7秒清空队列(此时线程2还在取数据),
该例子主要为了测试线程使用队列进行交互。
*/
#include <boost/thread/thread.hpp>
#include <boost/lockfree/queue.hpp>
#include <iostream>
#include <unistd.h>
#include <stdio.h>

#include <boost/atomic.hpp>

boost::lockfree::queue<int> queue(128);

const int iterations = 100;

void clear_queue();

/*
*Funcition:producer
*Description:一个用于每隔一秒向队列主添加数据并在添加完100组数据后等待7秒清空队列的线程处理函数
*Input:none
*Output:none
*/
void producer(void)
{
for (int i = 0; i != iterations; ++i) {
int value = ++producer_count;
while (!queue.bounded_push(value));
printf("\nadd %d\n",value);
sleep(1);
}
sleep(7);
clear_queue();
}

/*
*Function:clear_queue
*Description:一个用于清空队列的函数
*Input:none
*Output:none
*/
void clear_queue()
{
int value;
while(queue.pop(value));
printf("clear\n");
}

/*
*Function:consumer
*Description:一个用于每隔1秒从队列主取出一个数据的函数
*Input:none
*Output:none
*/
void consumer(void)
{
int value;
sleep(10);
while (queue.pop(value)) {
++consumer_count;
printf("del %d\n",value);
sleep(1);
}
printf("queue is empty\n");
}

/*
*Function:main
*Description:主函数
*Input:none
*Output:none
*/
int main(int argc, char* argv[])
{
using namespace std;
cout << "boost::lockfree::queue is ";
if (!queue.is_lock_free())
cout << "not ";
cout << "lockfree" << endl;
boost::thread th1(producer);
boost::thread th2(consumer);
th1.detach();
th2.detach();
while(1);
return 0;
}(2)、Makefile源代码
CC = g++
CFLAGS += -Wall
CINCLUDE = -I/usr/local/boost/x86/include
CLIB = -L/usr/local/boost/x86/lib
CLD = -lboost_thread -lboost_system

SRCS := \
free_queue.cpp
TARGET := test

all:$(TARGET)
$(TARGET):$(SRCS)
$(CC) $(CFLAGS) $(CINCLUDE) $(CLIB) $(CLD) $^ -o $@

(3)、编译测试
执行make进行编译,编译后运行./test进行运行测试。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐