1 | /*
|
---|
2 | * multithread_producer.cpp
|
---|
3 | *
|
---|
4 | * Created on: 10 окт. 2013 г.
|
---|
5 | * Author: aleksander
|
---|
6 | */
|
---|
7 |
|
---|
8 | #include <boost/bind.hpp>
|
---|
9 | #include <boost/thread.hpp>
|
---|
10 | #include <boost/interprocess/ipc/message_queue.hpp>
|
---|
11 | #include <vector>
|
---|
12 | boost::mutex mutex;
|
---|
13 |
|
---|
14 | void send(boost::interprocess::message_queue* q) {
|
---|
15 | // boost::mutex::scoped_lock lock(mutex);
|
---|
16 | char buff;
|
---|
17 | for (int i = 0; i < 10000; i++) {
|
---|
18 | q->send(&buff, 1, 0);
|
---|
19 | }
|
---|
20 | std::cout<<"writer thread complete"<<std::endl;
|
---|
21 | }
|
---|
22 |
|
---|
23 | void receive(boost::interprocess::message_queue* q) {
|
---|
24 | char buff;
|
---|
25 | size_t size;
|
---|
26 | unsigned int priority;
|
---|
27 | do {
|
---|
28 | q->receive(&buff, 1, size, priority);
|
---|
29 | } while (size > 0);
|
---|
30 | std::cout<<"reader thread complete"<<std::endl;
|
---|
31 | }
|
---|
32 |
|
---|
33 | const int THREAD_COUNT = 2;
|
---|
34 | int main(int argc, char **argv) {
|
---|
35 |
|
---|
36 | try {
|
---|
37 | char queue_name[] = "queue_test";
|
---|
38 | boost::interprocess::message_queue::remove(queue_name);
|
---|
39 | boost::interprocess::message_queue mq(boost::interprocess::open_or_create, queue_name, 100, 1);
|
---|
40 |
|
---|
41 | std::vector<boost::thread*> threads;
|
---|
42 |
|
---|
43 | for (int i = 0; i < THREAD_COUNT; i++) {
|
---|
44 | threads.push_back(new boost::thread(boost::bind(send, &mq)));
|
---|
45 | }
|
---|
46 | threads.push_back(new boost::thread(boost::bind(receive, &mq)));
|
---|
47 |
|
---|
48 | for (int i = 0; i < THREAD_COUNT; i++) {
|
---|
49 | threads[i]->join();
|
---|
50 | }
|
---|
51 |
|
---|
52 | char buff;
|
---|
53 |
|
---|
54 | mq.send(&buff, 0, 0);
|
---|
55 |
|
---|
56 | threads[THREAD_COUNT]->join();
|
---|
57 | std::cout << "complete" << std::endl;
|
---|
58 | } catch (std::exception &e) {
|
---|
59 | std::cout << "error " << e.what() << std::endl;
|
---|
60 | }
|
---|
61 | return 0;
|
---|
62 | }
|
---|