-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdata_creator_writer_shm.cpp
62 lines (56 loc) · 1.59 KB
/
data_creator_writer_shm.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include "shared_data.h"
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <thread>
using namespace boost::interprocess;
int main()
{
// Remove shared memory on construction and destruction
struct shm_remove
{
shm_remove()
{
shared_memory_object::remove("MySharedMemory");
}
~shm_remove()
{
shared_memory_object::remove("MySharedMemory");
}
} remover;
// Create a shared memory object.
shared_memory_object shm(create_only, "MySharedMemory", read_write);
// Set size
shm.truncate(sizeof(Image));
// Map the whole shared memory in this process
mapped_region region(shm, read_write);
// Get the address of the mapped region
void* addr = region.get_address();
// Construct the shared structure in memory
Image* image = new (addr) Image;
// Write some pixels
{
scoped_lock<interprocess_mutex> lock(image->mutex);
image->data.fill(10);
}
// Wait until the other process ends
while (1)
{
scoped_lock<interprocess_mutex> lock(image->mutex);
if (std::all_of(image->data.begin(),
image->data.end(),
[](auto pixel) { return pixel == 11; }))
{
break;
}
else
{
lock.unlock();
std::this_thread::sleep_for(std::chrono::seconds{1});
}
}
return 0;
}