1 | // Copyright (C) 2011 Tim Blechmann |
---|---|
2 | // |
3 | // Distributed under the Boost Software License, Version 1.0. (See |
4 | // accompanying file LICENSE_1_0.txt or copy at |
5 | // http://www.boost.org/LICENSE_1_0.txt) |
6 | |
7 | #include <cstdlib> //std::system |
8 | #include <sstream> |
9 | |
10 | #include <boost/interprocess/managed_shared_memory.hpp> |
11 | #include <boost/lockfree/stack.hpp> |
12 | #include <boost/thread/thread.hpp> |
13 | |
14 | using namespace boost::interprocess; |
15 | typedef allocator<int, managed_shared_memory::segment_manager> ShmemAllocator; |
16 | typedef boost::lockfree::stack<int, |
17 | boost::lockfree::allocator<ShmemAllocator>, |
18 | boost::lockfree::capacity<2048> |
19 | > stack; |
20 | |
21 | int main (int argc, char *argv[]) |
22 | { |
23 | if(argc == 1){ |
24 | struct shm_remove |
25 | { |
26 | shm_remove() { shared_memory_object::remove(filename: "MySharedMemory"); } |
27 | ~shm_remove(){ shared_memory_object::remove(filename: "MySharedMemory"); } |
28 | } remover; |
29 | |
30 | managed_shared_memory segment(create_only, "MySharedMemory", 65536); |
31 | ShmemAllocator alloc_inst (segment.get_segment_manager()); |
32 | |
33 | stack * queue = segment.construct<stack>(name: "stack")(alloc_inst); |
34 | for (int i = 0; i != 1024; ++i) |
35 | queue->push(v: i); |
36 | |
37 | std::string s(argv[0]); s += " child "; |
38 | if(0 != std::system(command: s.c_str())) |
39 | return 1; |
40 | |
41 | while (!queue->empty()) |
42 | boost::thread::yield(); |
43 | return 0; |
44 | } else { |
45 | managed_shared_memory segment(open_only, "MySharedMemory"); |
46 | stack * queue = segment.find<stack>(name: "stack").first; |
47 | |
48 | int from_queue; |
49 | for (int i = 0; i != 1024; ++i) { |
50 | bool success = queue->pop(ret&: from_queue); |
51 | assert (success); |
52 | assert (from_queue == 1023 - i); |
53 | } |
54 | segment.destroy<stack>(name: "stack"); |
55 | } |
56 | return 0; |
57 | } |
58 |