提交 ecbd77fa 编写于 作者: cosmicing's avatar cosmicing

更新00-ProgramElement/1-NolockQueue/examples/jamfile,...

更新00-ProgramElement/1-NolockQueue/examples/jamfile, 00-ProgramElement/1-NolockQueue/examples/message_q.cpp
上级 f6a1c621
#include "lock_free_queue.hpp"
#include <chrono>
#include <string>
#include <cstdio>
using namespace std;
struct Message {
int id;
int type;
string notify;
};
int main()
{
add::LockFreeQueue<Message, 30> q;
auto product_func = [&q]() {
int id = 0;
while (id < 100) {
Message e = { id, 0, "" };
switch(id % 3) {
case 0:
e.type = 0;
e.notify = "message type 0";
break;
case 1:
e.type = 1;
e.notify = "message type 1";
break;
case 2:
e.type = 2;
e.notify = "message type 2";
break;
}
if (!q.push(e)) {
std::this_thread::sleep_for(std::chrono::microseconds(1));
continue;
}
id++;
}
};
auto consume_func = [&q]() {
int i = 0;
while (i < 100) {
Message e;
if (!q.pop(e)) {
std::this_thread::sleep_for(std::chrono::microseconds(1));
continue;
}
printf("message[%d]: type:%d, content:%s\n", e.id, e.type, e.notify.c_str());
i++;
}
};
// 生产者
std::thread p1(product_func);
std::thread p2(product_func);
// 消费者
std::thread c1 (consume_func);
std::thread c2 (consume_func);
p1.join();
p2.join();
c1.join();
c2.join();
return 0;
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册