1 | #include <boost/thread.hpp>
|
---|
2 |
|
---|
3 | class Packet
|
---|
4 | {
|
---|
5 | public:
|
---|
6 | Packet(int i) : in(i) {}
|
---|
7 | int in;
|
---|
8 | };
|
---|
9 |
|
---|
10 | typedef boost::promise< Packet > packet_promise;
|
---|
11 | typedef boost::shared_ptr< packet_promise > packet_promise_shared_ptr;
|
---|
12 | typedef std::pair< unsigned long, packet_promise_shared_ptr > seq_promise_pair;
|
---|
13 | typedef std::map< unsigned long, packet_promise_shared_ptr > seq_to_promise_map;
|
---|
14 |
|
---|
15 | class Demo
|
---|
16 | {
|
---|
17 | private:
|
---|
18 | boost::thread setvalue_thread_;
|
---|
19 | seq_to_promise_map mymap_;
|
---|
20 | boost::mutex mymap_mutex_;
|
---|
21 | unsigned long counter_;
|
---|
22 |
|
---|
23 | public:
|
---|
24 | Demo() :
|
---|
25 | counter_(10),
|
---|
26 | setvalue_thread_(boost::bind(&Demo::do_calc_in_thread, this))
|
---|
27 | {
|
---|
28 | }
|
---|
29 |
|
---|
30 | packet_promise_shared_ptr calc()
|
---|
31 | {
|
---|
32 | packet_promise_shared_ptr ptrPromisePacket(new packet_promise());
|
---|
33 | boost::mutex::scoped_lock l(mymap_mutex_);
|
---|
34 | mymap_.insert(seq_promise_pair(counter_, ptrPromisePacket) );
|
---|
35 | counter_++;
|
---|
36 | return ptrPromisePacket;
|
---|
37 | }
|
---|
38 |
|
---|
39 | //calculate in a seperate thread and set_value(), loops forever
|
---|
40 | void do_calc_in_thread()
|
---|
41 | {
|
---|
42 | while(true)
|
---|
43 | {
|
---|
44 | {
|
---|
45 | boost::mutex::scoped_lock l(mymap_mutex_);
|
---|
46 | seq_to_promise_map::iterator value_in_map_iter = mymap_.begin();
|
---|
47 | for (value_in_map_iter; value_in_map_iter != mymap_.end(); value_in_map_iter++)
|
---|
48 | {
|
---|
49 | unsigned long in_counter = value_in_map_iter->first;
|
---|
50 | //printf("[%d] thread running set value\n", in_counter);
|
---|
51 | Packet resultPacket(in_counter);
|
---|
52 | value_in_map_iter->second->set_value(resultPacket); //make a copy
|
---|
53 | mymap_.erase(value_in_map_iter);
|
---|
54 | }
|
---|
55 | }
|
---|
56 | }
|
---|
57 | }
|
---|
58 |
|
---|
59 | };
|
---|
60 |
|
---|
61 | int main(int argc, char** argv)
|
---|
62 | {
|
---|
63 | Demo demo;
|
---|
64 | unsigned long testCounter=0;
|
---|
65 |
|
---|
66 | while(true)
|
---|
67 | {
|
---|
68 | packet_promise_shared_ptr packetPromisePtr = demo.calc();
|
---|
69 | boost::system_time const timeout = boost::get_system_time() + boost::posix_time::milliseconds(500);
|
---|
70 | boost::unique_future< Packet > pf = packetPromisePtr->get_future(); //often causes core-dump
|
---|
71 |
|
---|
72 | if (!pf.timed_wait_until(timeout))
|
---|
73 | {
|
---|
74 | printf("[%d] error \n", testCounter);
|
---|
75 | break;
|
---|
76 | }
|
---|
77 | else
|
---|
78 | {
|
---|
79 | Packet result = pf.get();
|
---|
80 | printf("[%d] ok : %d \n", testCounter, result.in);
|
---|
81 | }
|
---|
82 | testCounter++;
|
---|
83 | }
|
---|
84 |
|
---|
85 | }
|
---|