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 |
|
---|
12 | namespace bi = boost::interprocess;
|
---|
13 | using SharedMutex = bi::named_sharable_mutex;
|
---|
14 | using ReadLock = bi::sharable_lock<SharedMutex>;
|
---|
15 | using WriteLock = bi::scoped_lock<SharedMutex>;
|
---|
16 | using NewEntryCondition = bi::named_condition_any;
|
---|
17 |
|
---|
18 | constexpr char SHM_NAME[] = "shared_mem";
|
---|
19 | constexpr char MUT_NAME[] = "shm_mut";
|
---|
20 | constexpr char COND_NAME[] = "shm_cond";
|
---|
21 | constexpr char CUR_INT_NAME[] = "shm_int";
|
---|
22 |
|
---|
23 |
|
---|
24 | int main(int argc, char *argv[])
|
---|
25 | {
|
---|
26 | // Open the shared mem, condition variable, mutex
|
---|
27 | bi::managed_shared_memory segment(bi::open_only, SHM_NAME);
|
---|
28 | SharedMutex sh_mut(bi::open_only, MUT_NAME);
|
---|
29 | NewEntryCondition sh_cond(bi::open_only, COND_NAME);
|
---|
30 |
|
---|
31 | int& shared_int = *segment.find<int>("shared_int").first;
|
---|
32 | int copy_of_int = -1;
|
---|
33 |
|
---|
34 | for (int i=0;;i++) {
|
---|
35 | {
|
---|
36 | ReadLock r_lock( sh_mut );
|
---|
37 |
|
---|
38 | std::cout << "calling named_condition_any::wait()" << std::endl;
|
---|
39 | sh_cond.wait(
|
---|
40 | r_lock,
|
---|
41 | [&shared_int, ©_of_int]() {
|
---|
42 | std::cout << "checking predicate..." << std::endl;
|
---|
43 | return (copy_of_int < shared_int);
|
---|
44 | });
|
---|
45 |
|
---|
46 | copy_of_int = shared_int;
|
---|
47 | std::cout << "copy of int = " << copy_of_int << std::endl;
|
---|
48 | }
|
---|
49 |
|
---|
50 | }
|
---|
51 |
|
---|
52 | return 0;
|
---|
53 | }
|
---|