Ticket #12476: producer.cpp

File producer.cpp, 2.0 KB (added by Chris Evans <chris.evans@…>, 6 years ago)
Line 
1#include <thread>
2#include <chrono>
3#include <iostream>
4
5#include <boost/interprocess/sync/scoped_lock.hpp>
6#include <boost/interprocess/sync/named_mutex.hpp>
7#include <boost/interprocess/sync/named_sharable_mutex.hpp>
8#include <boost/interprocess/sync/sharable_lock.hpp>
9#include <boost/interprocess/sync/named_condition_any.hpp>
10#include <boost/interprocess/managed_shared_memory.hpp>
11
12namespace bi = boost::interprocess;
13using SharedMutex = bi::named_sharable_mutex;
14using ReadLock = bi::sharable_lock<SharedMutex>;
15using WriteLock = bi::scoped_lock<SharedMutex>;
16using NewEntryCondition = bi::named_condition_any;
17
18constexpr char SHM_NAME[] = "shared_mem";
19constexpr char MUT_NAME[] = "shm_mut";
20constexpr char COND_NAME[] = "shm_cond";
21constexpr char CUR_INT_NAME[] = "shm_int";
22
23
24int main(int argc, char *argv[])
25{
26 // Remove the shared mem, condition variable, mutex
27 struct shm_remove
28 {
29 shm_remove() { bi::shared_memory_object::remove( SHM_NAME ); }
30 ~shm_remove() { bi::shared_memory_object::remove( SHM_NAME ); }
31 } remover;
32 struct mut_remove
33 {
34 mut_remove() { SharedMutex::remove(MUT_NAME); }
35 ~mut_remove() { SharedMutex::remove(MUT_NAME); }
36 } mut_remover;
37
38 struct cond_remove
39 {
40 cond_remove() { NewEntryCondition::remove(COND_NAME); }
41 ~cond_remove() { NewEntryCondition::remove(COND_NAME); }
42 } cond_remover;
43
44 // Create the shared mem, condition variable, mutex
45 bi::managed_shared_memory segment(bi::create_only, SHM_NAME, 2*65536);
46 SharedMutex sh_mut(bi::create_only, MUT_NAME);
47 NewEntryCondition sh_cond(bi::create_only, COND_NAME);
48
49 int& shared_int = *segment.construct<int>("shared_int")(0);
50
51 for (int i=0;;i++) {
52 std::this_thread::sleep_for(std::chrono::seconds(2));
53
54 {
55 WriteLock w_lock( sh_mut );
56
57 shared_int = i;
58 std::cout << "set shared_int to: " << shared_int << std::endl;
59
60 sh_cond.notify_all();
61 }
62
63 }
64
65
66
67 return 0;
68}