| 1 | ////////////////////////////////////////////////////////////////////////////// |
|---|---|
| 2 | // |
| 3 | // (C) Copyright Ion Gaztanaga 2006-2012. Distributed under the Boost |
| 4 | // Software License, Version 1.0. (See accompanying file |
| 5 | // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
| 6 | // |
| 7 | // See http://www.boost.org/libs/interprocess for documentation. |
| 8 | // |
| 9 | ////////////////////////////////////////////////////////////////////////////// |
| 10 | |
| 11 | //[doc_anonymous_semaphoreA |
| 12 | #include <boost/interprocess/shared_memory_object.hpp> |
| 13 | #include <boost/interprocess/mapped_region.hpp> |
| 14 | #include <iostream> |
| 15 | #include "doc_anonymous_semaphore_shared_data.hpp" |
| 16 | |
| 17 | using namespace boost::interprocess; |
| 18 | |
| 19 | int main () |
| 20 | { |
| 21 | //Remove shared memory on construction and destruction |
| 22 | struct shm_remove |
| 23 | { |
| 24 | shm_remove() { shared_memory_object::remove(filename: "MySharedMemory"); } |
| 25 | ~shm_remove(){ shared_memory_object::remove(filename: "MySharedMemory"); } |
| 26 | } remover; |
| 27 | //<- |
| 28 | (void)remover; |
| 29 | //-> |
| 30 | |
| 31 | //Create a shared memory object. |
| 32 | shared_memory_object shm |
| 33 | (create_only //only create |
| 34 | ,"MySharedMemory"//name |
| 35 | ,read_write //read-write mode |
| 36 | ); |
| 37 | |
| 38 | //Set size |
| 39 | shm.truncate(length: sizeof(shared_memory_buffer)); |
| 40 | |
| 41 | //Map the whole shared memory in this process |
| 42 | mapped_region region |
| 43 | (shm //What to map |
| 44 | ,read_write //Map it as read-write |
| 45 | ); |
| 46 | |
| 47 | //Get the address of the mapped region |
| 48 | void * addr = region.get_address(); |
| 49 | |
| 50 | //Construct the shared structure in memory |
| 51 | shared_memory_buffer * data = new (addr) shared_memory_buffer; |
| 52 | |
| 53 | const int NumMsg = 100; |
| 54 | |
| 55 | //Insert data in the array |
| 56 | for(int i = 0; i < NumMsg; ++i){ |
| 57 | data->nempty.wait(); |
| 58 | data->mutex.wait(); |
| 59 | data->items[i % shared_memory_buffer::NumItems] = i; |
| 60 | data->mutex.post(); |
| 61 | data->nstored.post(); |
| 62 | } |
| 63 | |
| 64 | return 0; |
| 65 | } |
| 66 | //] |
| 67 | |
| 68 |
