• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1[/
2 / Copyright (c) 2005-2012 Ion Gaztanaga
3 /
4 / Distributed under the Boost Software License, Version 1.0. (See accompanying
5 / file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 /]
7
8[library Boost.Interprocess
9    [quickbook 1.5]
10    [authors [Gaztanaga, Ion]]
11    [copyright 2005-2015 Ion Gaztanaga]
12    [id interprocess]
13    [dirname interprocess]
14    [purpose Interprocess communication utilities]
15    [license
16        Distributed under the Boost Software License, Version 1.0.
17        (See accompanying file LICENSE_1_0.txt or copy at
18        [@http://www.boost.org/LICENSE_1_0.txt])
19    ]
20]
21
22[section:intro Introduction]
23
24[*Boost.Interprocess] simplifies the use of common interprocess communication
25and synchronization mechanisms and offers a wide range of them:
26
27* Shared memory.
28* Memory-mapped files.
29* Semaphores, mutexes, condition variables and upgradable mutex types to place
30  them in shared memory and memory mapped files.
31* Named versions of those synchronization objects, similar to UNIX/Windows
32  sem_open/CreateSemaphore API.
33* File locking.
34* Relative pointers.
35* Message queues.
36
37[*Boost.Interprocess] also offers higher-level interprocess mechanisms to allocate
38dynamically portions of a shared memory or a memory mapped file (in general,
39to allocate portions of a fixed size memory segment). Using these mechanisms,
40[*Boost.Interprocess] offers useful tools to construct C++ objects, including
41STL-like containers, in shared memory and memory mapped files:
42
43* Dynamic creation of anonymous and named objects in a shared memory or memory
44  mapped file.
45* STL-like containers compatible with shared memory/memory-mapped files.
46* STL-like allocators ready for shared memory/memory-mapped files implementing
47  several memory allocation patterns (like pooling).
48
49[section:introduction_building_interprocess Building Boost.Interprocess]
50
51There is no need to compile [*Boost.Interprocess], since it's
52a header only library. Just include your Boost header directory in your
53compiler include path.
54
55[*Boost.Interprocess] depends on
56[@http://www.boost.org/libs/date_time/ [*Boost.DateTime]], which needs
57separate compilation. However, the subset used by [*Boost.Interprocess] does
58not need any separate compilation so the user can define `BOOST_DATE_TIME_NO_LIB`
59to avoid Boost from trying to automatically link the [*Boost.DateTime].
60
61In POSIX systems, [*Boost.Interprocess] uses pthread system calls to implement
62classes like mutexes, condition variables, etc... In some operating systems,
63these POSIX calls are implemented in separate libraries that are not automatically
64linked by the compiler. For example, in some Linux systems POSIX pthread functions
65are implemented in `librt.a` library, so you might need to add that library
66when linking an executable or shared library that uses [*Boost.Interprocess].
67If you obtain linking errors related to those pthread functions, please revise
68your system's documentation to know which library implements them.
69
70[endsect]
71
72[section:tested_compilers Tested compilers]
73
74[*Boost.Interprocess] has been tested in the following compilers/platforms:
75
76*  Visual C++ >= 7.1.
77*  GCC >= 4.1.
78
79[warning GCC < 4.3 and MSVC < 9.0 are deprecated and will be removed in the next version.]
80
81[endsect]
82
83[endsect]
84
85[section:quick_guide Quick Guide for the Impatient]
86
87[section:qg_memory_pool Using shared memory as a pool of unnamed memory blocks]
88
89You can just allocate a portion of a shared memory segment, copy the
90message to that buffer, send the offset of that portion of shared
91memory to another process, and you are done. Let's see the example:
92
93[import ../example/doc_ipc_message.cpp]
94[doc_ipc_message]
95
96[endsect]
97
98[section:qg_named_interprocess Creating named shared memory objects]
99
100You want to create objects in a shared memory segment, giving a string name to them so that
101any other process can find, use and delete them from the segment when the objects are not
102needed anymore. Example:
103
104[import ../example/doc_named_alloc.cpp]
105[doc_named_alloc]
106
107[endsect]
108
109[section:qg_offset_ptr Using an offset smart pointer for shared memory]
110
111[*Boost.Interprocess] offers offset_ptr smart pointer family
112as an offset pointer that stores the distance between the address of
113the offset pointer itself and the address of the pointed object.
114When offset_ptr is placed in a shared memory segment, it
115can point safely objects stored in the same shared
116memory segment, even if the segment is mapped in
117different base addresses in different processes.
118
119This allows placing objects with pointer members
120in shared memory. For example, if we want to create
121a linked list in shared memory:
122
123[import ../example/doc_offset_ptr.cpp]
124[doc_offset_ptr]
125
126To help with basic data structures, [*Boost.Interprocess] offers containers like vector,
127list, map, so you can avoid these manual data structures just like with standard containers.
128
129[endsect]
130
131[section:qg_interprocess_container Creating vectors in shared memory]
132
133[*Boost.Interprocess] allows creating complex objects in shared memory and memory
134mapped files. For example, we can construct STL-like containers in shared memory.
135To do this, we just need to create a special (managed) shared memory segment,
136declare a [*Boost.Interprocess] allocator and construct the vector in shared memory
137just if it was any other object.
138
139The class that allows this complex structures in shared memory is called
140[classref boost::interprocess::managed_shared_memory] and it's easy to use.
141Just execute this example without arguments:
142
143[import ../example/doc_spawn_vector.cpp]
144[doc_spawn_vector]
145
146The parent process will create an special shared memory class that allows easy construction
147of many complex data structures associated with a name. The parent process executes the same
148program with an additional argument so the child process opens the shared memory and uses
149the vector and erases it.
150
151[endsect]
152
153[section:qg_interprocess_map Creating maps in shared memory]
154
155Just like a vector, [*Boost.Interprocess] allows creating maps in
156shared memory and memory mapped files. The only difference is that
157like standard associative containers, [*Boost.Interprocess]'s map needs
158also the comparison functor when an allocator is passed in the constructor:
159
160[import ../example/doc_map.cpp]
161[doc_map]
162
163For a more advanced example including containers of containers, see the section
164[link interprocess.allocators_containers.containers_explained.containers_of_containers Containers of containers].
165
166[endsect]
167
168[endsect]
169
170[section:some_basic_explanations Some basic explanations]
171
172[section:processes_and_threads Processes And Threads]
173
174[*Boost.Interprocess] does not work only with processes but also with threads.
175[*Boost.Interprocess] synchronization mechanisms can synchronize threads
176from different processes, but also threads from the same process.
177
178[endsect]
179
180[section:sharing_information Sharing information between processes]
181
182In the traditional programming model an operating system has multiple processes
183running and each process has its own address space. To share information between
184processes we have several alternatives:
185
186* Two processes share information using a [*file]. To access to the data, each
187  process uses the usual file read/write mechanisms. When updating/reading
188  a file shared between processes, we need some sort of synchronization, to
189  protect readers from writers.
190
191* Two processes share information that resides in the [*kernel] of the operating
192  system. This is the case, for example, of traditional message queues. The
193  synchronization is guaranteed by the operating system kernel.
194
195* Two processes can share a [*memory] region. This is the case of classical
196  shared memory or memory mapped files. Once the processes set up the
197  memory region, the processes can read/write the data like any
198  other memory segment without calling the operating system's kernel. This
199  also requires some kind of manual synchronization between processes.
200
201[endsect]
202
203[section:persistence Persistence Of Interprocess Mechanisms]
204
205One of the biggest issues with interprocess communication mechanisms is the lifetime
206of the interprocess communication mechanism.
207It's important to know when an interprocess communication mechanism disappears from the
208system. In [*Boost.Interprocess], we can have 3 types of persistence:
209
210* [*Process-persistence]: The mechanism lasts until all the processes that have
211  opened the mechanism close it, exit or crash.
212
213* [*Kernel-persistence]: The mechanism exists until the kernel of the operating
214  system reboots or the mechanism is explicitly deleted.
215
216* [*Filesystem-persistence]: The mechanism exists until the mechanism is explicitly
217  deleted.
218
219Some native POSIX and Windows IPC mechanisms have different persistence so it's
220difficult to achieve portability between Windows and POSIX native mechanisms.
221[*Boost.Interprocess] classes have the following persistence:
222
223[table Boost.Interprocess Persistence Table
224   [[Mechanism] [Persistence]]
225   [[Shared memory]                 [Kernel or Filesystem]]
226   [[Memory mapped file]            [Filesystem]]
227   [[Process-shared mutex types]    [Process]]
228   [[Process-shared semaphore]      [Process]]
229   [[Process-shared condition]      [Process]]
230   [[File lock]                     [Process]]
231   [[Message queue]                 [Kernel or Filesystem]]
232   [[Named mutex]                   [Kernel or Filesystem]]
233   [[Named semaphore]               [Kernel or Filesystem]]
234   [[Named condition]               [Kernel or Filesystem]]
235]
236
237As you can see, [*Boost.Interprocess] defines some mechanisms with "Kernel or Filesystem"
238persistence. This is because POSIX allows this possibility to native interprocess
239communication implementations. One could, for example, implement
240shared memory using memory mapped files and obtain filesystem persistence (for example,
241there is no proper known way to emulate kernel persistence with a user library
242for Windows shared memory using native shared memory,
243or process persistence for POSIX shared memory, so the only portable way is to
244define "Kernel or Filesystem" persistence).
245
246[endsect]
247
248[section:names Names Of Interprocess Mechanisms]
249
250Some interprocess mechanisms are anonymous objects created in shared memory or
251memory-mapped files but other interprocess mechanisms need a name or identifier
252so that two unrelated processes can use the same interprocess mechanism object.
253Examples of this are shared memory, named mutexes and named semaphores (for example,
254native windows CreateMutex/CreateSemaphore API family).
255
256The name used to identify an interprocess mechanism is not portable, even between
257UNIX systems. For this reason, [*Boost.Interprocess] limits this name to a C++ variable
258identifier or keyword:
259
260*Starts with a letter, lowercase or uppercase, such as a letter from a to z or from
261 A to Z. Examples: ['Sharedmemory, sharedmemory, sHaReDmEmOrY...]
262*Can include letters, underscore, or digits. Examples: ['shm1, shm2and3, ShM3plus4...]
263
264[endsect]
265
266
267[section:constructors_destructors_and_resource_lifetime
268   Constructors, destructors and lifetime of Interprocess named resources]
269
270Named [*Boost.Interprocess] resources (shared memory, memory mapped files,
271named mutexes/conditions/semaphores) have kernel or filesystem persistency.
272This means that even if all processes that have opened those resources
273end, the resource will still be accessible to be opened again and the resource
274can only be destructed via an explicit call to their static member `remove` function.
275This behavior can be easily understood, since it's the same mechanism used
276by functions controlling file opening/creation/erasure:
277
278[table Boost.Interprocess-Filesystem Analogy
279   [[Named Interprocess resource] [Corresponding std file]  [Corresponding POSIX operation]]
280   [[Constructor]                 [std::fstream constructor][open]]
281   [[Destructor]                  [std::fstream destructor] [close]]
282   [[Member `remove`]             [None. `std::remove`]     [unlink]]
283]
284
285Now the correspondence between POSIX and Boost.Interprocess
286regarding shared memory and named semaphores:
287
288[table Boost.Interprocess-POSIX shared memory
289   [[`shared_memory_object` operation] [POSIX operation]]
290   [[Constructor]                      [shm_open]]
291   [[Destructor]                       [close]]
292   [[Member `remove`]                  [shm_unlink]]
293]
294
295[table Boost.Interprocess-POSIX named semaphore
296   [[`named_semaphore` operation]      [POSIX operation]]
297   [[Constructor]                      [sem_open]]
298   [[Destructor]                       [close]]
299   [[Member `remove`]                  [sem_unlink]]
300]
301
302The most important property is that [*destructors of named resources
303don't remove the resource from the system], they only liberate resources
304allocated by the system for use by the process for the named resource.
305[*To remove the resource from the system the programmer must use
306`remove`].
307
308[endsect]
309
310[section:permissions Permissions]
311
312Named resources offered by [*Boost.Interprocess] must cope with platform-dependant
313permission issues also present when creating files. If a programmer wants to
314shared shared memory, memory mapped files or named synchronization mechanisms
315(mutexes, semaphores, etc...) between users, it's necessary to specify
316those permissions. Sadly, traditional UNIX and Windows permissions are very
317different and [*Boost.Interprocess] does not try to standardize permissions,
318but does not ignore them.
319
320All named resource creation functions take an optional
321[classref boost::interprocess::permissions permissions object] that can be
322configured with platform-dependant permissions.
323
324Since each mechanism can be emulated through different mechanisms
325(a semaphore might be implement using mapped files or native semaphores)
326permissions types could vary when the implementation of a named resource
327changes (eg.: in Windows mutexes require `synchronize permissions`, but
328that's not the case of files).
329To avoid this, [*Boost.Interprocess] relies on file-like permissions,
330requiring file read-write-delete permissions to open named synchronization mechanisms
331(mutex, semaphores, etc.) and appropriate read or read-write-delete permissions for
332shared memory. This approach has two advantages: it's similar to the UNIX philosophy
333and the programmer does not need to know how the named resource is implemented.
334
335[endsect]
336
337[endsect]
338
339[section:sharedmemorybetweenprocesses Sharing memory between processes]
340
341[section:sharedmemory Shared memory]
342
343[section:shared_memory_what_is What is shared memory?]
344
345Shared memory is the fastest interprocess communication mechanism.
346The operating system maps a memory segment in the address space of several
347processes, so that several processes can read and write in that memory segment
348without calling operating system functions. However, we need some kind of
349synchronization between processes that read and write shared memory.
350
351Consider what happens when a server process wants to send an HTML file to a client process
352that resides in the same machine using network mechanisms:
353
354* The server must read the file to memory and pass it to the network functions, that
355  copy that memory to the OS's internal memory.
356
357* The client uses the network functions to copy the data from the OS's internal memory
358  to its own memory.
359
360As we can see, there are two copies, one from memory to the network and another one
361from the network to memory. And those copies are made using operating system calls
362that normally are expensive. Shared memory avoids this overhead, but we need to
363synchronize both processes:
364
365* The server maps a shared memory in its address space and also gets access to a
366  synchronization mechanism. The server obtains exclusive access to the memory using
367  the synchronization mechanism and copies the file to memory.
368
369* The client maps the shared memory in its address space. Waits until the server releases
370  the exclusive access and uses the data.
371
372Using shared memory, we can avoid two data copies, but we have to synchronize the access
373to the shared memory segment.
374
375[endsect]
376
377[section:shared_memory_steps Creating memory segments that can be shared between processes]
378
379To use shared memory, we have to perform 2 basic steps:
380
381* Request to the operating system a memory segment that can be shared between
382processes. The user can create/destroy/open this memory using a [*shared memory object]:
383['An object that represents memory that can be mapped concurrently into the
384  address space of more than one process.].
385
386* Associate a part of that memory or the whole memory with the address space of the
387  calling process. The operating system looks for a big enough memory address range
388  in the calling process' address space and marks that address range as an
389  special range. Changes in that address range are automatically seen
390  by other process that also have mapped the same shared memory object.
391
392Once the two steps have been successfully completed, the process can start writing to
393and reading from the address space to send to and receive data from other processes.
394Now, let's see how can we do this using [*Boost.Interprocess]:
395
396[endsect]
397
398[section:shared_memory_header Header]
399
400To manage shared memory, you just need to include the following header:
401
402[c++]
403
404   #include <boost/interprocess/shared_memory_object.hpp>
405
406[endsect]
407
408[section:shared_memory_creating_shared_memory_segments Creating shared memory segments]
409
410As we've mentioned we have to use the `shared_memory_object` class to create, open
411and destroy shared memory segments that can be mapped by several processes. We can
412specify the access mode of that shared memory object (read only or read-write),
413just as if it was a file:
414
415* Create a shared memory segment. Throws if already created:
416
417[c++]
418
419      using boost::interprocess;
420      shared_memory_object shm_obj
421         (create_only                  //only create
422         ,"shared_memory"              //name
423         ,read_write                   //read-write mode
424         );
425
426* To open or create a shared memory segment:
427
428[c++]
429
430      using boost::interprocess;
431      shared_memory_object shm_obj
432         (open_or_create               //open or create
433         ,"shared_memory"              //name
434         ,read_only                    //read-only mode
435         );
436
437* To only open a shared memory segment. Throws if does not exist:
438
439[c++]
440
441      using boost::interprocess;
442      shared_memory_object shm_obj
443         (open_only                    //only open
444         ,"shared_memory"              //name
445         ,read_write                   //read-write mode
446         );
447
448When a shared memory object is created, its size is 0.
449To set the size of the shared memory, the user must use the `truncate` function
450call, in a shared memory that has been opened with read-write attributes:
451
452[c++]
453
454      shm_obj.truncate(10000);
455
456As shared memory has kernel or filesystem persistence, the user must explicitly
457destroy it. The `remove` operation might fail returning
458false if the shared memory does not exist, the file is open or the file is
459still memory mapped by other processes:
460
461[c++]
462
463      using boost::interprocess;
464      shared_memory_object::remove("shared_memory");
465
466
467For more details regarding `shared_memory_object` see the
468[classref boost::interprocess::shared_memory_object] class reference.
469
470[endsect]
471
472[section:shared_memory_mapping_shared_memory_segments Mapping Shared Memory Segments]
473
474Once created or opened, a process just has to map the shared memory object in the process'
475address space. The user can map the whole shared memory or just part of it. The
476mapping process is done using the `mapped_region` class. The class represents
477a memory region that has been mapped from a shared memory or from other devices
478that have also mapping capabilities (for example, files). A `mapped_region` can be
479created from any `memory_mappable` object and as you might imagine, `shared_memory_object`
480is a `memory_mappable` object:
481
482[c++]
483
484      using boost::interprocess;
485      std::size_t ShmSize = ...
486
487      //Map the second half of the memory
488      mapped_region region
489         ( shm                      //Memory-mappable object
490         , read_write               //Access mode
491         , ShmSize/2                //Offset from the beginning of shm
492         , ShmSize-ShmSize/2        //Length of the region
493         );
494
495      //Get the address of the region
496      region.get_address();
497
498      //Get the size of the region
499      region.get_size();
500
501The user can specify the offset from the mappable object where the mapped region
502should start and the size of the mapped region. If no offset or size is specified,
503the whole mappable object (in this case, shared memory) is mapped. If the offset
504is specified, but not the size, the mapped region covers from the offset until
505the end of the mappable object.
506
507For more details regarding `mapped_region` see the
508[classref boost::interprocess::mapped_region] class reference.
509
510[endsect]
511
512[section:shared_memory_a_simple_example A Simple Example]
513
514Let's see a simple example of shared memory use. A server process creates a
515shared memory object, maps it and initializes all the bytes to a value. After that,
516a client process opens the shared memory, maps it, and checks
517that the data is correctly initialized:
518
519[import ../example/doc_shared_memory.cpp]
520[doc_shared_memory]
521
522[endsect]
523
524[section:emulation Emulation for systems without shared memory objects]
525
526[*Boost.Interprocess] provides portable shared memory in terms of POSIX
527semantics. Some operating systems don't support shared memory as defined by
528POSIX:
529
530*  Windows operating systems provide shared memory using memory backed by the
531   paging file but the lifetime semantics are different from the ones
532   defined by POSIX (see [link interprocess.sharedmemorybetweenprocesses.sharedmemory.windows_shared_memory
533   Native windows shared memory] section for more information).
534
535*  Some UNIX systems don't fully support POSIX shared memory objects at all.
536
537In those platforms, shared memory is emulated with mapped files created
538in a "boost_interprocess" folder created in a temporary files directory.
539In Windows platforms, if "Common AppData" key is present
540in the registry, "boost_interprocess" folder is created in that directory
541(in XP usually "C:\Documents and Settings\All Users\Application Data" and
542in Vista "C:\ProgramData").
543For Windows platforms without that registry key and Unix systems, shared memory is
544created in the system temporary files directory ("/tmp" or similar).
545
546Because of this emulation, shared memory has filesystem lifetime in some
547of those systems.
548
549[endsect]
550
551[section:removing Removing shared memory]
552
553[classref boost::interprocess::shared_memory_object shared_memory_object]
554provides a static `remove` function to remove a shared memory objects.
555
556This function [*can] fail if the shared memory objects does not exist or
557it's opened by another process. Note that this function is similar to the
558standard C `int remove(const char *path)` function. In UNIX systems,
559`shared_memory_object::remove` calls `shm_unlink`:
560
561*  The function will remove the name of the shared memory object
562named by the string pointed to by name.
563
564*  If one or more references to the shared memory object exist when
565is unlinked, the name will be removed before the function returns, but the
566removal of the memory object contents will be postponed until all open and
567map references to the shared memory object have been removed.
568
569*  Even if the object continues to exist after the last function call, reuse of
570the name will subsequently cause the creation of a
571[classref boost::interprocess::shared_memory_object] instance to behave as if no
572shared memory object of this name exists (that is, trying to open an object
573with that name will fail and an object of the same name can be created again).
574
575In Windows operating systems, current version supports an usually acceptable emulation
576of the UNIX unlink behaviour: the file is renamed with a random name and marked as ['to
577be deleted when the last open handle is closed].
578
579[endsect]
580
581[section:anonymous_shared_memory Anonymous shared memory for UNIX systems]
582
583Creating a shared memory segment and mapping it can be a bit tedious when several
584processes are involved. When processes are related via `fork()` operating system
585call in UNIX systems a simpler method is available using anonymous shared memory.
586
587This feature has been implemented in UNIX systems mapping the device `\dev\zero` or
588just using the `MAP_ANONYMOUS` in a POSIX conformant `mmap` system call.
589
590This feature is wrapped in [*Boost.Interprocess] using the `anonymous_shared_memory()`
591function, which returns a `mapped_region` object holding an anonymous shared memory
592segment that can be shared by related processes.
593
594Here is an example:
595
596[import ../example/doc_anonymous_shared_memory.cpp]
597[doc_anonymous_shared_memory]
598
599Once the segment is created, a `fork()` call can
600be used so that `region` is used to communicate two related processes.
601
602[endsect]
603
604[section:windows_shared_memory Native windows shared memory]
605
606Windows operating system also offers shared memory, but the lifetime of this
607shared memory is very different to kernel or filesystem lifetime. The shared memory
608is created backed by the pagefile and it's automatically destroyed when the last
609process attached to the shared memory is destroyed.
610
611Because of this reason, there is no effective way to simulate kernel or filesystem
612persistence using native windows shared memory and [*Boost.Interprocess] emulates
613shared memory using memory mapped files. This assures portability between POSIX
614and Windows operating systems.
615
616However, accessing native windows shared memory is a common request of
617[*Boost.Interprocess] users because they want to access
618to shared memory created with other process that don't use
619[*Boost.Interprocess]. In order to manage the native windows shared memory
620[*Boost.Interprocess] offers the
621[classref boost::interprocess::windows_shared_memory windows_shared_memory] class.
622
623Windows shared memory creation is a bit different from portable shared memory
624creation: the size of the segment must be specified when creating the object and
625can't be specified through `truncate` like with the shared memory object.
626Take in care that when the last process attached to a shared memory is destroyed
627[*the shared memory is destroyed] so there is [*no persistency] with native windows
628shared memory.
629
630Sharing memory between services and user applications is also different. To share memory
631between services and user applications the name of the shared memory must start with the
632global namespace prefix `"Global\\"`. This global namespace enables processes on multiple
633client sessions to communicate with a service application. The server component can create
634the shared memory in the global namespace. Then a client session can use the "Global\" prefix
635to open that memory.
636
637The creation of a shared memory object in the global namespace from a session other than
638session zero is a privileged operation.
639
640Let's repeat the same example presented for the portable shared memory object:
641A server process creates a
642shared memory object, maps it and initializes all the bytes to a value. After that,
643a client process opens the shared memory, maps it, and checks
644that the data is correctly initialized. Take in care that [*if the server exits before
645the client connects to the shared memory the client connection will fail], because
646the shared memory segment is destroyed when no proces is attached to the memory.
647
648This is the server process:
649
650[import ../example/doc_windows_shared_memory.cpp]
651[doc_windows_shared_memory]
652
653As we can see, native windows shared memory needs synchronization to make sure
654that the shared memory won't be destroyed before the client is launched.
655
656[endsect]
657
658[section:xsi_shared_memory XSI shared memory]
659
660In many UNIX systems, the OS offers another shared memory memory mechanism, XSI
661(X/Open System Interfaces) shared memory segments, also known as "System V" shared memory.
662This shared memory mechanism is quite popular and portable, and it's not based in file-mapping
663semantics, but it uses special functions (`shmget`, `shmat`, `shmdt`, `shmctl`...).
664
665Unlike POSIX shared memory segments, XSI shared memory segments are not identified by names but
666by 'keys' usually created with `ftok`. XSI shared memory segments have kernel lifetime and
667must be explicitly removed. XSI shared memory does not support copy-on-write and partial shared memory mapping
668but it supports anonymous shared memory.
669
670[*Boost.Interprocess] offers simple ([classref boost::interprocess::xsi_shared_memory xsi_shared_memory])
671and managed ([classref boost::interprocess::managed_xsi_shared_memory managed_xsi_shared_memory])
672shared memory classes to ease the use of XSI shared memory. It also wraps key creation with the
673simple [classref boost::interprocess::xsi_key xsi_key] class.
674
675Let's repeat the same example presented for the portable shared memory object:
676A server process creates a shared memory object, maps it and initializes all the bytes to a value. After that,
677a client process opens the shared memory, maps it, and checks
678that the data is correctly initialized.
679
680This is the server process:
681
682[import ../example/doc_xsi_shared_memory.cpp]
683[doc_xsi_shared_memory]
684
685[endsect]
686
687[endsect]
688
689[section:mapped_file Memory Mapped Files]
690
691[section:mapped_file_what_is What is a memory mapped file?]
692
693File mapping is the association of a file's contents with a portion of the address space
694of a process. The system creates a file mapping to associate the file and the address
695space of the process. A mapped region is the portion of address space that the process
696uses to access the file's contents. A single file mapping can have several mapped regions,
697so that the user can associate parts of the file with the address space of the process
698without mapping the entire file in the address space, since the file can be bigger
699than the whole address space of the process (a 9GB DVD image file in a usual 32
700bit systems). Processes read from and write to
701the file using pointers, just like with dynamic memory. File mapping has the following
702advantages:
703
704* Uniform resource use. Files and memory can be treated using the same functions.
705* Automatic file data synchronization and cache from the OS.
706* Reuse of C++ utilities (STL containers, algorithms) in files.
707* Shared memory between two or more applications.
708* Allows efficient work with a large files, without mapping the whole file into memory
709* If several processes use the same file mapping to create mapped regions of a file, each
710  process' views contain identical copies of the file on disk.
711
712File mapping is not only used for interprocess communication, it can be used also to
713simplify file usage, so the user does not need to use file-management functions to
714write the file. The user just writes data to the process memory, and the operating
715systems dumps the data to the file.
716
717When two processes map the same file in memory, the memory that one process writes is
718seen by another process, so memory mapped files can be used as an interprocess
719communication mechanism. We can say that memory-mapped files offer the same interprocess
720communication services as shared memory with the addition of filesystem persistence.
721However, as the operating system has to synchronize the file contents with the memory
722contents, memory-mapped files are not as fast as shared memory.
723
724[endsect]
725
726[section:mapped_file_steps Using mapped files]
727
728To use memory-mapped files, we have to perform 2 basic steps:
729
730* Create a mappable object that represent an already created file of the
731  filesystem. This object will be used to create multiple mapped regions of the
732  the file.
733
734* Associate the whole file or parts of the file with the address space of the
735  calling process. The operating system looks for a big enough memory address range
736  in the calling process' address space and marks that address range as an
737  special range. Changes in that address range are automatically seen
738  by other process that also have mapped the same file and those changes
739  are also transferred to the disk automatically.
740
741Once the two steps have been successfully completed, the process can start writing to
742and reading from the address space to send to and receive data from other processes
743and synchronize the file's contents with the changes made to the mapped region.
744Now, let's see how can we do this using [*Boost.Interprocess]:
745
746[endsect]
747
748[section:mapped_file_header Header]
749
750To manage mapped files, you just need to include the following header:
751
752[c++]
753
754   #include <boost/interprocess/file_mapping.hpp>
755
756[endsect]
757
758[section:mapped_file_creating_file Creating a file mapping]
759
760First, we have to link a file's contents with the process' address space. To do
761this, we have to create a mappable object that represents that file. This is
762achieved in [*Boost.Interprocess] creating a `file_mapping` object:
763
764[c++]
765
766      using boost::interprocess;
767      file_mapping m_file
768         ("/usr/home/file"       //filename
769         ,read_write             //read-write mode
770         );
771
772Now we can use the newly created object to create mapped regions. For more details
773regarding this class see the
774[classref boost::interprocess::file_mapping] class reference.
775
776[endsect]
777
778[section:mapped_file_mapping_regions Mapping File's Contents In Memory]
779
780After creating a file mapping, a process just has to map the shared memory in the
781process' address space. The user can map the whole shared memory or just part of it.
782The mapping process is done using the `mapped_region` class. as we have said before
783The class represents a memory region that has been mapped from a shared memory or from other
784devices that have also mapping capabilities:
785
786[c++]
787
788      using boost::interprocess;
789      std::size_t FileSize = ...
790
791      //Map the second half of the file
792      mapped_region region
793         ( m_file                   //Memory-mappable object
794         , read_write               //Access mode
795         , FileSize/2               //Offset from the beginning of shm
796         , FileSize-FileSize/2      //Length of the region
797         );
798
799      //Get the address of the region
800      region.get_address();
801
802      //Get the size of the region
803      region.get_size();
804
805
806The user can specify the offset from the file where the mapped region
807should start and the size of the mapped region. If no offset or size is specified,
808the whole file is mapped. If the offset is specified, but not the size,
809the mapped region covers from the offset until the end of the file.
810
811If several processes map the same file, and a process modifies a memory range
812from a mapped region that is also mapped by other process, the changes are
813inmedially visible to other processes. However, the file contents on disk are
814not updated immediately, since that would hurt performance (writing to disk
815is several times slower than writing to memory). If the user wants to make sure
816that file's contents have been updated, it can flush a range from the view to disk.
817When the function returns, the flushing process has started but there is no guarantee that
818all data has been written to disk:
819
820[c++]
821
822      //Flush the whole region
823      region.flush();
824
825      //Flush from an offset until the end of the region
826      region.flush(offset);
827
828      //Flush a memory range starting on an offset
829      region.flush(offset, size);
830
831Remember that the offset is [*not] an offset on the file, but an offset in the
832mapped region. If a region covers the second half of a file and flushes the
833whole region, only the half of the file is guaranteed to have been flushed.
834
835For more details regarding `mapped_region` see the
836[classref boost::interprocess::mapped_region] class reference.
837
838[endsect]
839
840[section:mapped_file_a_simple_example A Simple Example]
841
842Let's reproduce the same example described in the shared memory section, using
843memory mapped files. A server process creates a shared
844memory segment, maps it and initializes all the bytes to a value. After that,
845a client process opens the shared memory, maps it, and checks
846that the data is correctly initialized::
847
848[import ../example/doc_file_mapping.cpp]
849[doc_file_mapping]
850
851[endsect]
852
853[endsect]
854
855[section:mapped_region More About Mapped Regions]
856
857[section:mapped_region_one_class One Class To Rule Them All]
858
859As we have seen, both `shared_memory_object` and `file_mapping` objects can be used
860to create `mapped_region` objects. A mapped region created from a shared memory
861object or a file mapping are the same class and this has many advantages.
862
863One can, for example, mix in STL containers mapped regions from shared memory
864and memory mapped files. Libraries that only depend on mapped regions can
865be used to work with shared memory or memory mapped files without recompiling them.
866
867[endsect]
868
869[section:mapped_region_address_mapping Mapping Address In Several Processes]
870
871In the example we have seen, the file or shared memory contents are mapped
872to the address space of the process, but the address was chosen by the operating
873system.
874
875If several processes map the same file/shared memory, the mapping address will be
876surely different in each process. Since each process might have used its address space
877in a different way (allocation of more or less dynamic memory, for example), there is
878no guarantee that the file/shared memory is going to be mapped in the same address.
879
880If two processes map the same object in different addresses, this invalidates the use
881of pointers in that memory, since the pointer (which is an absolute address) would
882only make sense for the process that wrote it. The solution for this is to use offsets
883(distance) between objects instead of pointers: If two objects are placed in the same
884shared memory segment by one process, [*the address of each object will be different]
885in another process but [*the distance between them (in bytes) will be the same].
886
887So the first advice when mapping shared memory and memory mapped files is to avoid
888using raw pointers, unless you know what you are doing. Use offsets between data or
889relative pointers to obtain pointer functionality when an object placed in a mapped
890region wants to point to an object placed in the same mapped region. [*Boost.Interprocess]
891offers a smart pointer called [classref boost::interprocess::offset_ptr] that
892can be safely placed in shared memory and that can be used to point to another
893object placed in the same shared memory / memory mapped file.
894
895[endsect]
896
897[section:mapped_region_fixed_address_mapping Fixed Address Mapping]
898
899The use of relative pointers is less efficient than using raw pointers, so if a user
900can succeed mapping the same file or shared memory object in the same address in two
901processes, using raw pointers can be a good idea.
902
903To map an object in a fixed address, the user can specify that address in the
904`mapped region`'s constructor:
905
906[c++]
907
908   mapped_region region ( shm                         //Map shared memory
909                        , read_write                  //Map it as read-write
910                        , 0                           //Map from offset 0
911                        , 0                           //Map until the end
912                        , (void*)0x3F000000           //Map it exactly there
913                        );
914
915However, the user can't map the region in any address, even if the address is not
916being used. The offset parameter that marks the start of the mapping region
917is also limited. These limitations are explained in the next section.
918
919[endsect]
920
921[section:mapped_region_mapping_problems Mapping Offset And Address Limitations]
922
923As mentioned, the user can't map the memory mappable object at any address and it can
924specify the offset of the mappable object that is equivalent to the start of the mapping
925region to an arbitrary value.
926Most operating systems limit the mapping address and the offset of the mappable object
927to a multiple of a value called [*page size]. This is due to the fact that the
928[*operating system performs mapping operations over whole pages].
929
930If fixed mapping address is used, ['offset] and ['address]
931parameters should be multiples of that value.
932This value is, typically, 4KB or 8KB for 32 bit operating systems.
933
934[c++]
935
936   //These might fail because the offset is not a multiple of the page size
937   //and we are using fixed address mapping
938   mapped_region region1( shm                   //Map shared memory
939                        , read_write            //Map it as read-write
940                        , 1                     //Map from offset 1
941                        , 1                     //Map 1 byte
942                        , (void*)0x3F000000     //Aligned mapping address
943                        );
944
945   //These might fail because the address is not a multiple of the page size
946   mapped_region region2( shm                   //Map shared memory
947                        , read_write            //Map it as read-write
948                        , 0                     //Map from offset 0
949                        , 1                     //Map 1 byte
950                        , (void*)0x3F000001     //Not aligned mapping address
951                        );
952
953Since the operating system performs mapping operations over whole pages, specifying
954a mapping ['size] or ['offset] that are not multiple of the page size will waste
955more resources than necessary. If the user specifies the following 1 byte mapping:
956
957[c++]
958
959   //Map one byte of the shared memory object.
960   //A whole memory page will be used for this.
961   mapped_region region ( shm                    //Map shared memory
962                        , read_write             //Map it as read-write
963                        , 0                      //Map from offset 0
964                        , 1                      //Map 1 byte
965                        );
966
967The operating system will reserve a whole page that will not be reused by any
968other mapping so we are going to waste [*(page size - 1)] bytes. If we want
969to use efficiently operating system resources, we should create regions whose size
970is a multiple of [*page size] bytes. If the user specifies the following two
971mapped regions for a file with which has `2*page_size` bytes:
972
973   //Map the first quarter of the file
974   //This will use a whole page
975   mapped_region region1( shm                //Map shared memory
976                        , read_write         //Map it as read-write
977                        , 0                  //Map from offset 0
978                        , page_size/2        //Map page_size/2 bytes
979                        );
980
981   //Map the rest of the file
982   //This will use a 2 pages
983   mapped_region region2( shm                //Map shared memory
984                        , read_write         //Map it as read-write
985                        , page_size/2        //Map from offset 0
986                        , 3*page_size/2      //Map the rest of the shared memory
987                        );
988
989In this example, a half of the page is wasted in the first mapping and another
990half is wasted in the second because the offset is not a multiple of the
991page size. The mapping with the minimum resource usage would be to map whole pages:
992
993   //Map the whole first half: uses 1 page
994   mapped_region region1( shm                //Map shared memory
995                        , read_write         //Map it as read-write
996                        , 0                  //Map from offset 0
997                        , page_size          //Map a full page_size
998                        );
999
1000   //Map the second half: uses 1 page
1001   mapped_region region2( shm                //Map shared memory
1002                        , read_write         //Map it as read-write
1003                        , page_size          //Map from offset 0
1004                        , page_size          //Map the rest
1005                        );
1006
1007How can we obtain the [*page size]? The `mapped_region` class has a static
1008function that returns that value:
1009
1010[c++]
1011
1012   //Obtain the page size of the system
1013   std::size_t page_size = mapped_region::get_page_size();
1014
1015The operating system might also limit the number of mapped memory regions per
1016process or per system.
1017
1018[endsect]
1019
1020[endsect]
1021
1022[section:mapped_region_object_limitations Limitations When Constructing Objects In Mapped Regions]
1023
1024When two processes create a mapped region of the same mappable object, two processes
1025can communicate writing and reading that memory. A process could construct a C++ object
1026in that memory so that the second process can use it. However, a mapped region shared
1027by multiple processes, can't hold any C++ object, because not every class is ready
1028to be a process-shared object, specially, if the mapped region is mapped in different
1029address in each process.
1030
1031[section:offset_pointer Offset pointers instead of raw pointers]
1032
1033When placing objects in a mapped region and mapping
1034that region in different address in every process,
1035raw pointers are a problem since they are only valid for the
1036process that placed them there. To solve this, [*Boost.Interprocess] offers
1037a special smart pointer that can be used instead of a raw pointer.
1038So user classes containing raw pointers (or Boost smart pointers, that
1039internally own a raw pointer) can't be safely placed in a process shared
1040mapped region. These pointers must be replaced with offset pointers, and
1041these pointers must point only to objects placed in the same mapped region
1042if you want to use these shared objects from different processes.
1043
1044Of course, a pointer placed in a mapped region shared between processes should
1045only point to an object of that mapped region. Otherwise, the pointer would
1046point to an address that it's only valid one process and other
1047processes may crash when accessing to that address.
1048
1049[endsect]
1050
1051[section:references_forbidden References forbidden]
1052
1053References suffer from the same problem as pointers
1054(mainly because they are implemented as pointers).
1055However, it is not possible to create a fully workable
1056smart reference currently in C++ (for example,
1057`operator .()` can't be overloaded). Because of this,
1058if the user wants to put an object in shared memory,
1059the object can't have any (smart or not) reference
1060as a member.
1061
1062References will only work if the mapped region is mapped in the same
1063base address in all processes sharing a memory segment.
1064Like pointers, a reference placed in a mapped region should only point
1065to an object of that mapped region.
1066
1067[endsect]
1068
1069[section:virtuality_limitation Virtuality forbidden]
1070
1071The virtual table pointer and the virtual table
1072are in the address space of the process
1073that constructs the object, so if we place a class
1074with a virtual function or virtual base class, the virtual
1075pointer placed in shared memory will be invalid for other processes
1076and they will crash.
1077
1078This problem is very difficult to solve, since each process needs a
1079different virtual table pointer and the object that contains that pointer
1080is shared across many processes. Even if we map the mapped region in
1081the same address in every process, the virtual table can be in a different
1082address in every process. To enable virtual functions for objects
1083shared between processes, deep compiler changes are needed and virtual
1084functions would suffer a performance hit. That's why
1085[*Boost.Interprocess] does not have any plan to support virtual function
1086and virtual inheritance in mapped regions shared between processes.
1087
1088[endsect]
1089
1090[section:statics_warning Be careful with static class members]
1091
1092Static members of classes are global objects shared by
1093all instances of the class. Because of this, static
1094members are implemented as global variables in processes.
1095
1096When constructing a class with static members, each process
1097has its own copy of the static member, so updating a static
1098member in one process does not change the value of the static
1099member the another process. So be careful with these classes. Static
1100members are not dangerous if they are just constant variables initialized
1101when the process starts, but they don't change at all (for example,
1102when used like enums) and their value is the same for all processes.
1103
1104[endsect]
1105
1106[endsect]
1107
1108[endsect]
1109
1110[section:offset_ptr Mapping Address Independent Pointer: offset_ptr]
1111
1112When creating shared memory and memory mapped files to communicate two
1113processes the memory segment can be mapped in a different address in each process:
1114
1115[c++]
1116
1117   #include<boost/interprocess/shared_memory_object.hpp>
1118
1119   // ...
1120
1121   using boost::interprocess;
1122
1123   //Open a shared memory segment
1124   shared_memory_object shm_obj
1125      (open_only                    //open or create
1126      ,"shared_memory"              //name
1127      ,read_only   //read-only mode
1128      );
1129
1130   //Map the whole shared memory
1131   mapped_region region
1132      ( shm                         //Memory-mappable object
1133      , read_write                  //Access mode
1134      );
1135
1136   //This address can be different in each process
1137   void *addr = region.get_address();
1138
1139This makes the creation of complex objects in mapped regions difficult: a C++
1140class instance placed in a mapped region might have a pointer pointing to
1141another object also placed in the mapped region. Since the pointer stores an
1142absolute address, that address is only valid for the process that placed
1143the object there unless all processes map the mapped region in the same
1144address.
1145
1146To be able to simulate pointers in mapped regions, users must use [*offsets]
1147(distance between objects) instead of absolute addresses. The offset between
1148two objects in a mapped region is the same for any process that maps the
1149mapped region, even if that region is placed in different base addresses.
1150To facilitate the use of offsets, [*Boost.Interprocess] offers
1151[classref boost::interprocess::offset_ptr offset_ptr].
1152
1153[classref boost::interprocess::offset_ptr offset_ptr]
1154wraps all the background operations
1155needed to offer a pointer-like interface. The class interface is
1156inspired in Boost Smart Pointers and this smart pointer
1157stores the offset (distance in bytes)
1158between the pointee's address and it's own `this` pointer.
1159Imagine a structure in a common
116032 bit processor:
1161
1162[c++]
1163
1164   struct structure
1165   {
1166      int               integer1;   //The compiler places this at offset 0 in the structure
1167      offset_ptr<int>   ptr;        //The compiler places this at offset 4 in the structure
1168      int               integer2;   //The compiler places this at offset 8 in the structure
1169   };
1170
1171   //...
1172
1173   structure s;
1174
1175   //Assign the address of "integer1" to "ptr".
1176   //"ptr" will store internally "-4":
1177   //    (char*)&s.integer1 - (char*)&s.ptr;
1178   s.ptr = &s.integer1;
1179
1180   //Assign the address of "integer2" to "ptr".
1181   //"ptr" will store internally "4":
1182   //    (char*)&s.integer2 - (char*)&s.ptr;
1183   s.ptr = &s.integer2;
1184
1185
1186One of the big problems of
1187`offset_ptr` is the representation of the null pointer. The null pointer
1188can't be safely represented like an offset, since the absolute address 0
1189is always outside of the mapped region. Due to the fact that the segment can be mapped
1190in a different base address in each process the distance between the address 0
1191and `offset_ptr` is different for every process.
1192
1193Some implementations choose the offset 0 (that is, an `offset_ptr`
1194pointing to itself) as the null pointer pointer representation
1195but this is not valid for many use cases
1196since many times structures like linked lists or nodes from STL containers
1197point to themselves (the
1198end node in an empty container, for example) and 0 offset value
1199is needed. An alternative is to store, in addition to the offset, a boolean
1200to indicate if the pointer is null. However, this increments the size of the
1201pointer and hurts performance.
1202
1203In consequence,
1204[classref boost::interprocess::offset_ptr offset_ptr] defines offset 1
1205as the null pointer, meaning that this class [*can't] point to the byte
1206after its own ['this] pointer:
1207
1208[c++]
1209
1210   using namespace boost::interprocess;
1211
1212   offset_ptr<char> ptr;
1213
1214   //Pointing to the next byte of it's own address
1215   //marks the smart pointer as null.
1216   ptr = (char*)&ptr + 1;
1217
1218   //ptr is equal to null
1219   assert(!ptr);
1220
1221   //This is the same as assigning the null value...
1222   ptr = 0;
1223
1224   //ptr is also equal to null
1225   assert(!ptr);
1226
1227
1228In practice, this limitation is not important, since a user almost never
1229wants to point to this address.
1230
1231[classref boost::interprocess::offset_ptr offset_ptr]
1232offers all pointer-like operations and
1233random_access_iterator typedefs, so it can be used in STL
1234algorithms requiring random access iterators and detected via traits.
1235For more information about the members and operations of the class, see
1236[classref boost::interprocess::offset_ptr offset_ptr reference].
1237
1238[endsect]
1239
1240[section:synchronization_mechanisms Synchronization mechanisms]
1241
1242[section:synchronization_mechanisms_overview Synchronization mechanisms overview]
1243
1244As mentioned before, the ability to shared memory between processes through memory
1245mapped files or shared memory objects is not very useful if the access to that
1246memory can't be effectively synchronized. This is the same problem that happens with
1247thread-synchronization mechanisms, where heap memory and global variables are
1248shared between threads, but the access to these resources needs to be synchronized
1249typically through mutex and condition variables. [*Boost.Threads] implements these
1250synchronization utilities between threads inside the same process. [*Boost.Interprocess]
1251implements similar mechanisms to synchronize threads from different processes.
1252
1253[section:synchronization_mechanisms_named_vs_anonymous Named And Anonymous Synchronization Mechanisms]
1254
1255[*Boost.Interprocess] presents two types of synchronization objects:
1256
1257* [*Named utilities]: When two processes want
1258  to create an object of such type, both processes must ['create] or ['open] an object
1259  using the same name. This is similar to creating or opening files: a process creates
1260  a file with using a `fstream` with the name ['filename] and another process opens
1261  that file using another `fstream` with the same ['filename] argument.
1262  [*Each process uses a different object to access to the resource, but both processes
1263  are using the same underlying resource].
1264
1265* [*Anonymous utilities]: Since these utilities have no name, two processes must
1266  share [*the same object] through shared memory or memory mapped files. This is
1267  similar to traditional thread synchronization objects: [*Both processes share the
1268  same object]. Unlike thread synchronization, where global variables and heap
1269  memory is shared between threads of the same process, sharing objects between
1270  two threads from different process can be only possible through mapped regions
1271  that map the same mappable resource (for example, shared memory or memory mapped files).
1272
1273Each type has it's own advantages and disadvantages:
1274
1275* Named utilities are easier to handle for simple synchronization tasks, since both process
1276  don't have to create a shared memory region and construct the synchronization mechanism there.
1277
1278* Anonymous utilities can be serialized to disk when using memory mapped objects obtaining
1279  automatic persistence of synchronization utilities. One could construct a synchronization
1280  utility in a memory mapped file, reboot the system, map the file again, and use the
1281  synchronization utility again without any problem. This can't be achieved with named
1282  synchronization utilities.
1283
1284The main interface difference between named and anonymous utilities are the constructors.
1285Usually anonymous utilities have only one constructor, whereas the named utilities have
1286several constructors whose first argument is a special type that requests creation,
1287opening or opening or creation of the underlying resource:
1288
1289[c++]
1290
1291  using namespace boost::interprocess;
1292
1293  //Create the synchronization utility. If it previously
1294  //exists, throws an error
1295  NamedUtility(create_only, ...)
1296
1297  //Open the synchronization utility. If it does not previously
1298  //exist, it's created.
1299  NamedUtility(open_or_create, ...)
1300
1301  //Open the synchronization utility. If it does not previously
1302  //exist, throws an error.
1303  NamedUtility(open_only, ...)
1304
1305On the other hand the anonymous synchronization utility can only
1306be created and the processes must synchronize using other mechanisms
1307who creates the utility:
1308
1309[c++]
1310
1311  using namespace boost::interprocess;
1312
1313  //Create the synchronization utility.
1314  AnonymousUtility(...)
1315
1316[endsect]
1317
1318[section:synchronization_mechanisms_types Types Of Synchronization Mechanisms]
1319
1320Apart from its named/anonymous nature, [*Boost.Interprocess] presents the following
1321synchronization utilities:
1322
1323* Mutexes (named and anonymous)
1324* Condition variables (named and anonymous)
1325* Semaphores (named and anonymous)
1326* Upgradable mutexes
1327* File locks
1328
1329[endsect]
1330
1331[endsect]
1332
1333[section:mutexes Mutexes]
1334
1335[section:mutexes_whats_a_mutex What's A Mutex?]
1336
1337['Mutex] stands for [*mut]ual [*ex]clusion and it's the most basic form of
1338synchronization between processes.
1339Mutexes guarantee that only one thread can lock a given mutex. If a code section
1340is surrounded by a mutex locking and unlocking, it's guaranteed that only a thread
1341at a time executes that section of code.
1342When that thread [*unlocks] the mutex, other threads can enter to that code
1343region:
1344
1345[c++]
1346
1347   //The mutex has been previously constructed
1348
1349   lock_the_mutex();
1350
1351   //This code will be executed only by one thread
1352   //at a time.
1353
1354   unlock_the_mutex();
1355
1356A mutex can also be [*recursive] or [*non-recursive]:
1357
1358* Recursive mutexes can be locked several times by the same thread. To fully unlock the
1359  mutex, the thread has to unlock the mutex the same times it has locked it.
1360
1361* Non-recursive mutexes can't be locked several times by the same thread. If a mutex
1362  is locked twice by a thread, the result is undefined, it might throw an error or
1363  the thread could be blocked forever.
1364
1365[endsect]
1366
1367[section:mutexes_mutex_operations Mutex Operations]
1368
1369All the mutex types from [*Boost.Interprocess] implement the following operations:
1370
1371[blurb ['[*void lock()]]]
1372
1373[*Effects:]
1374 The calling thread tries to obtain ownership of the mutex, and if another thread has ownership of the mutex, it waits until it can obtain the ownership. If a thread takes ownership of the mutex the mutex must be unlocked by the same thread. If the mutex supports recursive locking, the mutex must be unlocked the same number of times it is locked.
1375
1376[*Throws:] *interprocess_exception* on error.
1377
1378[blurb ['[*bool try_lock()]]]
1379
1380[*Effects:] The calling thread tries to obtain ownership of the mutex, and if another thread has ownership of the mutex returns immediately. If the mutex supports recursive locking, the mutex must be unlocked the same number of times it is locked.
1381
1382[*Returns:] If the thread acquires ownership of the mutex, returns true, if the another thread has ownership of the mutex, returns false.
1383
1384[*Throws:] *interprocess_exception* on error.
1385
1386[blurb ['[*bool timed_lock(const boost::posix_time::ptime &abs_time)]]]
1387
1388[*Effects:] The calling thread will try to obtain exclusive ownership of the mutex if it can do so in until the specified time is reached. If the mutex supports recursive locking, the mutex must be unlocked the same number of times it is locked.
1389
1390[*Returns:] If the thread acquires ownership of the mutex, returns true, if the timeout expires returns false.
1391
1392[*Throws:] *interprocess_exception* on error.
1393
1394[blurb ['[*void unlock()]]]
1395
1396[*Precondition:] The thread must have exclusive ownership of the mutex.
1397
1398[*Effects:] The calling thread releases the exclusive ownership of the mutex. If the mutex supports recursive locking, the mutex must be unlocked the same number of times it is locked.
1399
1400[*Throws:] An exception derived from *interprocess_exception* on error.
1401
1402[important `boost::posix_time::ptime` absolute time points used by Boost.Interprocess synchronization mechanisms
1403are UTC time points, not local time points]
1404
1405[endsect]
1406
1407[section:mutexes_interprocess_mutexes Boost.Interprocess Mutex Types And Headers]
1408
1409Boost.Interprocess offers the following mutex types:
1410
1411[c++]
1412
1413   #include <boost/interprocess/sync/interprocess_mutex.hpp>
1414
1415* [classref boost::interprocess::interprocess_mutex interprocess_mutex]: A non-recursive,
1416  anonymous mutex that can be placed in shared memory or memory mapped files.
1417
1418[c++]
1419
1420   #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
1421
1422* [classref boost::interprocess::interprocess_recursive_mutex interprocess_recursive_mutex]: A recursive,
1423  anonymous mutex that can be placed in shared memory or memory mapped files.
1424
1425[c++]
1426
1427   #include <boost/interprocess/sync/named_mutex.hpp>
1428
1429* [classref boost::interprocess::named_mutex named_mutex]: A non-recursive,
1430  named mutex.
1431
1432[c++]
1433
1434   #include <boost/interprocess/sync/named_recursive_mutex.hpp>
1435
1436* [classref boost::interprocess::named_recursive_mutex named_recursive_mutex]: A recursive,
1437  named mutex.
1438
1439[endsect]
1440
1441[section:mutexes_scoped_lock Scoped lock]
1442
1443It's very important to unlock a mutex after the process has read or written the data.
1444This can be difficult when dealing with exceptions, so usually mutexes are used
1445with a scoped lock, a class that can guarantee that a mutex will always be unlocked
1446even when an exception occurs. To use a scoped lock just include:
1447
1448[c++]
1449
1450   #include <boost/interprocess/sync/scoped_lock.hpp>
1451
1452Basically, a scoped lock calls [*unlock()] in its destructor, and a mutex is always
1453unlocked when an exception occurs. Scoped lock has many constructors to lock,
1454try_lock, timed_lock a mutex or not to lock it at all.
1455
1456
1457[c++]
1458
1459   using namespace boost::interprocess;
1460
1461   //Let's create any mutex type:
1462   MutexType mutex;
1463
1464   {
1465      //This will lock the mutex
1466      scoped_lock<MutexType> lock(mutex);
1467
1468      //Some code
1469
1470      //The mutex will be unlocked here
1471   }
1472
1473   {
1474      //This will try_lock the mutex
1475      scoped_lock<MutexType> lock(mutex, try_to_lock);
1476
1477      //Check if the mutex has been successfully locked
1478      if(lock){
1479         //Some code
1480      }
1481
1482      //If the mutex was locked it will be unlocked
1483   }
1484
1485   {
1486      boost::posix_time::ptime abs_time = ...
1487
1488      //This will timed_lock the mutex
1489      scoped_lock<MutexType> lock(mutex, abs_time);
1490
1491      //Check if the mutex has been successfully locked
1492      if(lock){
1493         //Some code
1494      }
1495
1496      //If the mutex was locked it will be unlocked
1497   }
1498
1499For more information, check the
1500[classref boost::interprocess::scoped_lock scoped_lock's reference].
1501
1502[important `boost::posix_time::ptime` absolute time points used by Boost.Interprocess synchronization mechanisms
1503are UTC time points, not local time points]
1504
1505[endsect]
1506
1507[section:mutexes_anonymous_example Anonymous mutex example]
1508
1509Imagine that two processes need to write traces to a cyclic buffer built
1510in shared memory. Each process needs to obtain exclusive access to the
1511cyclic buffer, write the trace and continue.
1512
1513To protect the cyclic buffer, we can store a process shared mutex in the
1514cyclic buffer. Each process will lock the mutex before writing the data and
1515will write a flag when ends writing the traces
1516(`doc_anonymous_mutex_shared_data.hpp` header):
1517
1518[import ../example/doc_anonymous_mutex_shared_data.hpp]
1519[doc_anonymous_mutex_shared_data]
1520
1521This is the process main process. Creates the shared memory, constructs
1522the cyclic buffer and start writing traces:
1523
1524[import ../example/comp_doc_anonymous_mutexA.cpp]
1525[doc_anonymous_mutexA]
1526
1527The second process opens the shared memory, obtains access to the cyclic buffer
1528and starts writing traces:
1529
1530[import ../example/comp_doc_anonymous_mutexB.cpp]
1531[doc_anonymous_mutexB]
1532
1533As we can see, a mutex is useful to protect data but not to notify an event to another
1534process. For this, we need a condition variable, as we will see in the next section.
1535
1536[endsect]
1537
1538[section:mutexes_named_example Named mutex example]
1539
1540Now imagine that two processes want to write a trace to a file. First they write
1541their name, and after that they write the message. Since the operating system can
1542interrupt a process in any moment we can mix parts of the messages of both processes,
1543so we need a way to write the whole message to the file atomically. To achieve this,
1544we can use a named mutex so that each process locks the mutex before writing:
1545
1546[import ../example/doc_named_mutex.cpp]
1547[doc_named_mutex]
1548
1549[endsect]
1550
1551[endsect]
1552
1553[section:conditions Conditions]
1554
1555[section:conditions_whats_a_condition What's A Condition Variable?]
1556
1557In the previous example, a mutex is used to ['lock] but we can't use it to
1558['wait] efficiently until the condition to continue is met. A condition variable
1559can do two things:
1560
1561*  [*wait]: The thread is blocked until some other thread notifies that it can
1562   continue because the condition that lead to waiting has disappeared.
1563
1564*  [*notify]: The thread sends a signal to one blocked thread or to all blocked
1565   threads to tell them that they the condition that provoked their wait has
1566   disappeared.
1567
1568Waiting in a condition variable is always associated with a mutex.
1569The mutex must be locked prior to waiting on the condition. When waiting
1570on the condition variable, the thread unlocks the mutex and waits [*atomically].
1571
1572When the thread returns from a wait function (because of a signal or a timeout,
1573for example) the mutex object is again locked.
1574
1575[endsect]
1576
1577[section:conditions_interprocess_conditions Boost.Interprocess Condition Types And Headers]
1578
1579Boost.Interprocess offers the following condition types:
1580
1581[c++]
1582
1583   #include <boost/interprocess/sync/interprocess_condition.hpp>
1584
1585* [classref boost::interprocess::interprocess_condition interprocess_condition]:
1586  An anonymous condition variable that can be placed in shared memory or memory
1587  mapped files to be used with [classref boost::interprocess::interprocess_mutex].
1588
1589[c++]
1590
1591   #include <boost/interprocess/sync/interprocess_condition_any.hpp>
1592
1593* [classref boost::interprocess::interprocess_condition_any interprocess_condition_any]:
1594  An anonymous condition variable that can be placed in shared memory or memory
1595  mapped files to be used with any lock type.
1596
1597[c++]
1598
1599   #include <boost/interprocess/sync/named_condition.hpp>
1600
1601* [classref boost::interprocess::named_condition named_condition]: A named
1602  condition variable to be used with [classref boost::interprocess::named_mutex named_mutex].
1603
1604[c++]
1605
1606   #include <boost/interprocess/sync/named_condition_any.hpp>
1607
1608* [classref boost::interprocess::named_condition named_condition]: A named
1609  condition variable to be used with any lock type.
1610
1611Named conditions are similar to anonymous conditions, but they are used in
1612combination with named mutexes. Several times, we don't want to store
1613synchronization objects with the synchronized data:
1614
1615*  We want to change the synchronization method (from interprocess
1616   to intra-process, or without any synchronization) using the same data.
1617   Storing the process-shared anonymous synchronization with the synchronized
1618   data would forbid this.
1619
1620*  We want to send the synchronized data through the network or any other
1621   communication method. Sending the process-shared synchronization objects
1622   wouldn't have any sense.
1623
1624[endsect]
1625
1626[section:conditions_anonymous_example Anonymous condition example]
1627
1628Imagine that a process that writes a trace to a simple shared memory buffer that
1629another process prints one by one. The first process writes the trace and waits
1630until the other process prints the data. To achieve this, we can use two
1631condition variables: the first one is used to block the sender until the second
1632process prints the message and the second one to block the receiver until the
1633buffer has a trace to print.
1634
1635The shared memory trace buffer (doc_anonymous_condition_shared_data.hpp):
1636
1637[import ../example/doc_anonymous_condition_shared_data.hpp]
1638[doc_anonymous_condition_shared_data]
1639
1640This is the process main process. Creates the shared memory, places there
1641the buffer and starts writing messages one by one until it writes "last message"
1642to indicate that there are no more messages to print:
1643
1644[import ../example/comp_doc_anonymous_conditionA.cpp]
1645[doc_anonymous_conditionA]
1646
1647The second process opens the shared memory and prints each message
1648until the "last message" message is received:
1649
1650[import ../example/comp_doc_anonymous_conditionB.cpp]
1651[doc_anonymous_conditionB]
1652
1653With condition variables, a process can block if it can't continue the work,
1654and when the conditions to continue are met another process can wake it.
1655
1656[endsect]
1657
1658[endsect]
1659
1660[section:semaphores Semaphores]
1661
1662[section:semaphores_whats_a_semaphores What's A Semaphore?]
1663
1664A semaphore is a synchronization mechanism between processes based in an internal
1665count that offers two basic operations:
1666
1667*  [*Wait]: Tests the value of the semaphore count, and waits if the value is less than or
1668   equal than 0. Otherwise, decrements the semaphore count.
1669
1670*  [*Post]: Increments the semaphore count. If any process is blocked, one of those processes
1671   is awoken.
1672
1673If the initial semaphore count is initialized to 1, a [*Wait] operation is equivalent to a
1674mutex locking and [*Post] is equivalent to a mutex unlocking. This type of semaphore is known
1675as a [*binary semaphore].
1676
1677Although semaphores can be used like mutexes, they have a unique feature: unlike mutexes,
1678a [*Post] operation need not be executed by the same thread/process that executed the
1679[*Wait] operation.
1680
1681[endsect]
1682
1683[section:semaphores_interprocess_semaphores Boost.Interprocess Semaphore Types And Headers]
1684
1685Boost.Interprocess offers the following semaphore types:
1686
1687[c++]
1688
1689   #include <boost/interprocess/sync/interprocess_semaphore.hpp>
1690
1691* [classref boost::interprocess::interprocess_semaphore interprocess_semaphore]:
1692  An anonymous semaphore that can be placed in shared memory or memory
1693  mapped files.
1694
1695[c++]
1696
1697   #include <boost/interprocess/sync/named_semaphore.hpp>
1698
1699* [classref boost::interprocess::named_semaphore named_semaphore]: A named
1700  semaphore.
1701
1702[endsect]
1703
1704[section:semaphores_anonymous_example Anonymous semaphore example]
1705
1706We will implement an integer array in shared memory that will be used to transfer data
1707from one process to another process. The first process will write some integers
1708to the array and the process will block if the array is full.
1709
1710The second process will copy the transmitted data to its own buffer, blocking if
1711there is no new data in the buffer.
1712
1713This is the shared integer array (doc_anonymous_semaphore_shared_data.hpp):
1714
1715[import ../example/doc_anonymous_semaphore_shared_data.hpp]
1716[doc_anonymous_semaphore_shared_data]
1717
1718This is the process main process. Creates the shared memory, places there
1719the integer array and starts integers one by one, blocking if the array
1720is full:
1721
1722[import ../example/comp_doc_anonymous_semaphoreA.cpp]
1723[doc_anonymous_semaphoreA]
1724
1725The second process opens the shared memory and copies the received integers
1726to it's own buffer:
1727
1728[import ../example/comp_doc_anonymous_semaphoreB.cpp]
1729[doc_anonymous_semaphoreB]
1730
1731The same interprocess communication can be achieved with a condition variables
1732and mutexes, but for several synchronization patterns, a semaphore is more
1733efficient than a mutex/condition combination.
1734
1735[endsect]
1736
1737[endsect]
1738
1739[section:sharable_upgradable_mutexes Sharable and Upgradable Mutexes]
1740
1741[section:upgradable_whats_a_mutex What's a Sharable and an Upgradable Mutex?]
1742
1743Sharable and upgradable mutex are special mutex types that offers more locking possibilities
1744than a normal mutex. Sometimes, we can distinguish between [*reading] the data and
1745[*modifying] the data. If just some threads need to modify the data, and a plain mutex
1746is used to protect the data from concurrent access, concurrency is pretty limited:
1747two threads that only read the data will be serialized instead of being executed
1748concurrently.
1749
1750If we allow concurrent access to threads that just read the data but we avoid
1751concurrent access between threads that read and modify or between threads that modify,
1752we can increase performance. This is specially true in applications where data reading
1753is more common than data modification and the synchronized data reading code needs
1754some time to execute. With a sharable mutex we can acquire 2 lock types:
1755
1756*  [*Exclusive lock]: Similar to a plain mutex. If a thread acquires an exclusive
1757   lock, no other thread can acquire any lock (exclusive or other) until the exclusive
1758   lock is released. If any thread other has any lock other than exclusive, a thread trying
1759   to acquire an exclusive lock will block.
1760   This lock will be acquired by threads that will modify the data.
1761
1762*  [*Sharable lock]: If a thread acquires a sharable lock, other threads
1763   can't acquire the exclusive lock. If any thread has acquired
1764   the exclusive lock a thread trying to acquire a sharable lock will block.
1765   This locking is executed by threads that just need to read the data.
1766
1767With an upgradable mutex we can acquire previous locks plus a new upgradable lock:
1768
1769*  [*Upgradable lock]: Acquiring an upgradable lock is similar to acquiring
1770   a [*privileged sharable lock]. If a thread acquires an upgradable lock, other threads
1771   can acquire a sharable lock. If any thread has acquired the exclusive or upgradable lock
1772   a thread trying to acquire an upgradable lock will block.
1773   A thread that has acquired an upgradable lock,
1774   is guaranteed to be able to acquire atomically an exclusive lock when other threads
1775   that have acquired a sharable lock release it. This is used for
1776   a thread that [*maybe] needs to modify the data, but usually just needs to read the data.
1777   This thread acquires the upgradable lock and other threads can acquire the sharable lock.
1778   If the upgradable thread reads the data and it has to modify it, the thread can be promoted
1779   to acquire the exclusive lock: when all sharable threads have released the sharable lock, the
1780   upgradable lock is atomically promoted to an exclusive lock. The newly promoted thread
1781   can modify the data and it can be sure that no other thread has modified it while
1782   doing the transition. [*Only 1 thread can acquire the upgradable
1783   (privileged reader) lock].
1784
1785To sum up:
1786
1787[table Locking Possibilities for a Sharable Mutex
1788   [[If a thread has acquired the...] [Other threads can acquire...]]
1789   [[Sharable lock]    [many sharable locks]]
1790   [[Exclusive lock]   [no locks]]
1791]
1792
1793[table Locking Possibilities for an Upgradable Mutex
1794   [[If a thread has acquired the...] [Other threads can acquire...]]
1795   [[Sharable lock]    [many sharable locks and 1 upgradable lock]]
1796   [[Upgradable lock]  [many sharable locks]]
1797   [[Exclusive lock]   [no locks]]
1798]
1799
1800[endsect]
1801
1802[section:upgradable_transitions Lock transitions for Upgradable Mutex]
1803
1804A sharable mutex has no option to change the acquired lock for another lock
1805atomically.
1806
1807On the other hand, for an upgradable mutex, a thread that has
1808acquired a lock can try to acquire another lock type atomically.
1809All lock transitions are not guaranteed to succeed. Even if a transition is guaranteed
1810to succeed, some transitions will block the thread waiting until other threads release
1811the sharable locks. [*Atomically] means that no other thread will acquire an Upgradable
1812or Exclusive lock in the transition, [*so data is guaranteed to remain unchanged]:
1813
1814[table Transition Possibilities for an Upgradable Mutex
1815   [[If a thread has acquired the...] [It can atomically release the previous lock and...]]
1816   [[Sharable lock]    [try to obtain (not guaranteed) immediately the Exclusive lock if no other thread has exclusive or upgrable lock]]
1817   [[Sharable lock]    [try to obtain (not guaranteed) immediately the Upgradable lock if no other thread has exclusive or upgrable lock]]
1818   [[Upgradable lock]  [obtain the Exclusive lock when all sharable locks are released]]
1819   [[Upgradable lock]  [obtain the Sharable lock immediately]]
1820   [[Exclusive lock]   [obtain the Upgradable lock immediately]]
1821   [[Exclusive lock]   [obtain the Sharable lock immediately]]
1822]
1823
1824As we can see, an upgradable mutex is a powerful synchronization utility that can improve
1825the concurrency. However, if most of the time we have to modify the data, or the
1826synchronized code section is very short, it's more efficient to use a plain mutex, since
1827it has less overhead. Upgradable lock shines when the synchronized code section is bigger
1828and there are more readers than modifiers.
1829
1830[endsect]
1831
1832[section:sharable_upgradable_mutexes_operations Upgradable Mutex Operations]
1833
1834All the upgradable mutex types from [*Boost.Interprocess] implement
1835the following operations:
1836
1837[section:sharable_upgradable_mutexes_operations_exclusive Exclusive Locking (Sharable & Upgradable Mutexes)]
1838
1839[blurb ['[*void lock()]]]
1840
1841[*Effects:]
1842The calling thread tries to obtain exclusive ownership of the mutex, and if
1843another thread has any ownership of the mutex (exclusive or other),
1844it waits until it can obtain the ownership.
1845
1846[*Throws:] *interprocess_exception* on error.
1847
1848[blurb ['[*bool try_lock()]]]
1849
1850[*Effects:]
1851The calling thread tries to acquire exclusive ownership of the mutex without
1852waiting. If no other thread has any ownership of the mutex (exclusive or other)
1853this succeeds.
1854
1855[*Returns:] If it can acquire exclusive ownership immediately returns true.
1856If it has to wait, returns false.
1857
1858[*Throws:] *interprocess_exception* on error.
1859
1860[blurb ['[*bool timed_lock(const boost::posix_time::ptime &abs_time)]]]
1861
1862[*Effects:]
1863The calling thread tries to acquire exclusive ownership of the mutex
1864waiting if necessary until no other thread has any ownership of the mutex
1865(exclusive or other) or abs_time is reached.
1866
1867[*Returns:] If acquires exclusive ownership, returns true. Otherwise
1868returns false.
1869
1870[*Throws:] *interprocess_exception* on error.
1871
1872[blurb ['[*void unlock()]]]
1873
1874[*Precondition:] The thread must have exclusive ownership of the mutex.
1875
1876[*Effects:] The calling thread releases the exclusive ownership of the mutex.
1877
1878[*Throws:] An exception derived from *interprocess_exception* on error.
1879
1880[endsect]
1881
1882[section:sharable_upgradable_mutexes_operations_sharable Sharable Locking (Sharable & Upgradable Mutexes)]
1883
1884[blurb ['[*void lock_sharable()]]]
1885
1886[*Effects:]
1887The calling thread tries to obtain sharable ownership of the mutex, and if
1888another thread has exclusive ownership of the mutex,
1889waits until it can obtain the ownership.
1890
1891[*Throws:] *interprocess_exception* on error.
1892
1893[blurb ['[*bool try_lock_sharable()]]]
1894
1895[*Effects:]
1896The calling thread tries to acquire sharable ownership of the mutex without
1897waiting. If no other thread has exclusive ownership of
1898the mutex this succeeds.
1899
1900[*Returns:] If it can acquire sharable ownership immediately returns true.
1901If it has to wait, returns false.
1902
1903[*Throws:] *interprocess_exception* on error.
1904
1905[blurb ['[*bool timed_lock_sharable(const boost::posix_time::ptime &abs_time)]]]
1906
1907[*Effects:]
1908The calling thread tries to acquire sharable ownership of the mutex
1909waiting if necessary until no other thread has exclusive
1910ownership of the mutex or abs_time is reached.
1911
1912[*Returns:] If acquires sharable ownership, returns true. Otherwise
1913returns false.
1914
1915[*Throws:] *interprocess_exception* on error.
1916
1917[blurb ['[*void unlock_sharable()]]]
1918
1919[*Precondition:] The thread must have sharable ownership of the mutex.
1920
1921[*Effects:] The calling thread releases the sharable ownership of the mutex.
1922
1923[*Throws:] An exception derived from *interprocess_exception* on error.
1924
1925[endsect]
1926
1927[section:upgradable_mutexes_operations_upgradable Upgradable Locking (Upgradable Mutex only)]
1928
1929[blurb ['[*void lock_upgradable()]]]
1930
1931[*Effects:]
1932The calling thread tries to obtain upgradable ownership of the mutex, and if
1933another thread has exclusive or upgradable ownership of the mutex,
1934waits until it can obtain the ownership.
1935
1936[*Throws:] *interprocess_exception* on error.
1937
1938[blurb ['[*bool try_lock_upgradable()]]]
1939
1940[*Effects:]
1941The calling thread tries to acquire upgradable ownership of the mutex without
1942waiting. If no other thread has exclusive or upgradable ownership of
1943the mutex this succeeds.
1944
1945[*Returns:] If it can acquire upgradable ownership immediately returns true.
1946If it has to wait, returns false.
1947
1948[*Throws:] *interprocess_exception* on error.
1949
1950[blurb ['[*bool timed_lock_upgradable(const boost::posix_time::ptime &abs_time)]]]
1951
1952[*Effects:]
1953The calling thread tries to acquire upgradable ownership of the mutex
1954waiting if necessary until no other thread has exclusive
1955ownership of the mutex or abs_time is reached.
1956
1957[*Returns:] If acquires upgradable ownership, returns true. Otherwise
1958returns false.
1959
1960[*Throws:] *interprocess_exception* on error.
1961
1962[blurb ['[*void unlock_upgradable()]]]
1963
1964[*Precondition:] The thread must have upgradable ownership of the mutex.
1965
1966[*Effects:] The calling thread releases the upgradable ownership of the mutex.
1967
1968[*Throws:] An exception derived from *interprocess_exception* on error.
1969
1970[endsect]
1971
1972[section:upgradable_mutexes_operations_demotions Demotions (Upgradable Mutex only)]
1973
1974[blurb ['[*void unlock_and_lock_upgradable()]]]
1975
1976[*Precondition:] The thread must have exclusive ownership of the mutex.
1977
1978[*Effects:] The thread atomically releases exclusive ownership and acquires upgradable
1979ownership. This operation is non-blocking.
1980
1981[*Throws:] An exception derived from *interprocess_exception* on error.
1982
1983[blurb ['[*void unlock_and_lock_sharable()]]]
1984
1985[*Precondition:] The thread must have exclusive ownership of the mutex.
1986
1987[*Effects:] The thread atomically releases exclusive ownership and acquires sharable
1988ownership. This operation is non-blocking.
1989
1990[*Throws:] An exception derived from *interprocess_exception* on error.
1991
1992[blurb ['[*void unlock_upgradable_and_lock_sharable()]]]
1993
1994[*Precondition:] The thread must have upgradable ownership of the mutex.
1995
1996[*Effects:] The thread atomically releases upgradable ownership and acquires sharable
1997ownership. This operation is non-blocking.
1998
1999[*Throws:] An exception derived from *interprocess_exception* on error.
2000
2001[endsect]
2002
2003[section:upgradable_mutexes_operations_promotions Promotions (Upgradable Mutex only)]
2004[blurb ['[*void unlock_upgradable_and_lock()]]]
2005
2006[*Precondition:] The thread must have upgradable ownership of the mutex.
2007
2008[*Effects:] The thread atomically releases upgradable ownership and acquires exclusive
2009ownership. This operation will block until all threads with sharable ownership release it.
2010
2011[*Throws:] An exception derived from *interprocess_exception* on error.[blurb ['[*bool try_unlock_upgradable_and_lock()]]]
2012
2013[*Precondition:] The thread must have upgradable ownership of the mutex.
2014
2015[*Effects:] The thread atomically releases upgradable ownership and tries to acquire exclusive
2016ownership. This operation will fail if there are threads with sharable ownership, but
2017it will maintain upgradable ownership.
2018
2019[*Returns:] If acquires exclusive ownership, returns true. Otherwise
2020returns false.
2021
2022[*Throws:] An exception derived from *interprocess_exception* on error.[blurb ['[*bool timed_unlock_upgradable_and_lock(const boost::posix_time::ptime &abs_time)]]]
2023
2024[*Precondition:] The thread must have upgradable ownership of the mutex.
2025
2026[*Effects:] The thread atomically releases upgradable ownership and tries to acquire
2027exclusive ownership, waiting if necessary until abs_time. This operation will fail
2028if there are threads with sharable ownership or timeout reaches, but it will maintain
2029upgradable ownership.
2030
2031[*Returns:] If acquires exclusive ownership, returns true. Otherwise
2032returns false.
2033
2034[*Throws:] An exception derived from *interprocess_exception* on error.[blurb ['[*bool try_unlock_sharable_and_lock()]]]
2035
2036[*Precondition:] The thread must have sharable ownership of the mutex.
2037
2038[*Effects:] The thread atomically releases sharable ownership and tries to acquire exclusive
2039ownership. This operation will fail if there are threads with sharable or upgradable ownership,
2040but it will maintain sharable ownership.
2041
2042[*Returns:] If acquires exclusive ownership, returns true. Otherwise
2043returns false.
2044
2045[*Throws:] An exception derived from *interprocess_exception* on error.[blurb ['[*bool try_unlock_sharable_and_lock_upgradable()]]]
2046
2047[*Precondition:] The thread must have sharable ownership of the mutex.
2048
2049[*Effects:] The thread atomically releases sharable ownership and tries to acquire upgradable
2050ownership. This operation will fail if there are threads with sharable or upgradable ownership,
2051but it will maintain sharable ownership.
2052
2053[*Returns:] If acquires upgradable ownership, returns true. Otherwise
2054returns false.
2055
2056[*Throws:] An exception derived from *interprocess_exception* on error.
2057
2058[important `boost::posix_time::ptime` absolute time points used by Boost.Interprocess synchronization mechanisms
2059are UTC time points, not local time points]
2060
2061[endsect]
2062
2063[endsect]
2064
2065[section:sharable_upgradable_mutexes_mutex_interprocess_mutexes Boost.Interprocess Sharable & Upgradable Mutex Types And Headers]
2066
2067Boost.Interprocess offers the following sharable mutex types:
2068
2069[c++]
2070
2071   #include <boost/interprocess/sync/interprocess_sharable_mutex.hpp>
2072
2073* [classref boost::interprocess::interprocess_sharable_mutex interprocess_sharable_mutex]: A non-recursive,
2074  anonymous sharable mutex that can be placed in shared memory or memory mapped files.
2075
2076[c++]
2077
2078   #include <boost/interprocess/sync/named_sharable_mutex.hpp>
2079
2080* [classref boost::interprocess::named_sharable_mutex named_sharable_mutex]: A non-recursive,
2081  named sharable mutex.
2082
2083Boost.Interprocess offers the following upgradable mutex types:
2084
2085[c++]
2086
2087   #include <boost/interprocess/sync/interprocess_upgradable_mutex.hpp>
2088
2089* [classref boost::interprocess::interprocess_upgradable_mutex interprocess_upgradable_mutex]: A non-recursive,
2090  anonymous upgradable mutex that can be placed in shared memory or memory mapped files.
2091
2092[c++]
2093
2094   #include <boost/interprocess/sync/named_upgradable_mutex.hpp>
2095
2096* [classref boost::interprocess::named_upgradable_mutex named_upgradable_mutex]: A non-recursive,
2097  named upgradable mutex.
2098
2099[endsect]
2100
2101[section:sharable_upgradable_locks Sharable Lock And Upgradable Lock]
2102
2103As with plain mutexes, it's important to release the acquired lock even in the presence
2104of exceptions. [*Boost.Interprocess] mutexes are best used with the
2105[classref boost::interprocess::scoped_lock scoped_lock] utility,
2106and this class only offers exclusive locking.
2107
2108As we have sharable locking and upgradable locking with upgradable mutexes, we have two new
2109utilities: [classref boost::interprocess::sharable_lock sharable_lock] and
2110[classref boost::interprocess::upgradable_lock upgradable_lock]. Both classes are similar to `scoped_lock`
2111but `sharable_lock` acquires the sharable lock in the constructor and `upgradable_lock`
2112acquires the upgradable lock in the constructor.
2113
2114These two utilities can be use with any synchronization object that offers the needed
2115operations. For example, a user defined mutex type with no upgradable locking features
2116can use `sharable_lock` if the synchronization object offers [*lock_sharable()] and
2117[*unlock_sharable()] operations:
2118
2119[section:upgradable_mutexes_lock_types Sharable Lock And Upgradable Lock Headers]
2120
2121[c++]
2122
2123   #include <boost/interprocess/sync/sharable_lock.hpp>
2124
2125[c++]
2126
2127   #include <boost/interprocess/sync/upgradable_lock.hpp>
2128
2129[endsect]
2130
2131`sharable_lock` calls [*unlock_sharable()] in its destructor, and
2132`upgradable_lock` calls [*unlock_upgradable()] in its destructor, so the
2133upgradable mutex is always unlocked when an exception occurs.
2134
2135[c++]
2136
2137   using namespace boost::interprocess;
2138
2139   SharableOrUpgradableMutex sh_or_up_mutex;
2140
2141   {
2142      //This will call lock_sharable()
2143      sharable_lock<SharableOrUpgradableMutex> lock(sh_or_up_mutex);
2144
2145      //Some code
2146
2147      //The mutex will be unlocked here
2148   }
2149
2150   {
2151      //This won't lock the mutex()
2152      sharable_lock<SharableOrUpgradableMutex> lock(sh_or_up_mutex, defer_lock);
2153
2154      //Lock it on demand. This will call lock_sharable()
2155      lock.lock();
2156
2157      //Some code
2158
2159      //The mutex will be unlocked here
2160   }
2161
2162   {
2163      //This will call try_lock_sharable()
2164      sharable_lock<SharableOrUpgradableMutex> lock(sh_or_up_mutex, try_to_lock);
2165
2166      //Check if the mutex has been successfully locked
2167      if(lock){
2168         //Some code
2169      }
2170      //If the mutex was locked it will be unlocked
2171   }
2172
2173   {
2174      boost::posix_time::ptime abs_time = ...
2175
2176      //This will call timed_lock_sharable()
2177      scoped_lock<SharableOrUpgradableMutex> lock(sh_or_up_mutex, abs_time);
2178
2179      //Check if the mutex has been successfully locked
2180      if(lock){
2181         //Some code
2182      }
2183      //If the mutex was locked it will be unlocked
2184   }
2185
2186   UpgradableMutex up_mutex;
2187
2188   {
2189      //This will call lock_upgradable()
2190      upgradable_lock<UpgradableMutex> lock(up_mutex);
2191
2192      //Some code
2193
2194      //The mutex will be unlocked here
2195   }
2196
2197   {
2198      //This won't lock the mutex()
2199      upgradable_lock<UpgradableMutex> lock(up_mutex, defer_lock);
2200
2201      //Lock it on demand. This will call lock_upgradable()
2202      lock.lock();
2203
2204      //Some code
2205
2206      //The mutex will be unlocked here
2207   }
2208
2209   {
2210      //This will call try_lock_upgradable()
2211      upgradable_lock<UpgradableMutex> lock(up_mutex, try_to_lock);
2212
2213      //Check if the mutex has been successfully locked
2214      if(lock){
2215         //Some code
2216      }
2217      //If the mutex was locked it will be unlocked
2218   }
2219
2220   {
2221      boost::posix_time::ptime abs_time = ...
2222
2223      //This will call timed_lock_upgradable()
2224      scoped_lock<UpgradableMutex> lock(up_mutex, abs_time);
2225
2226      //Check if the mutex has been successfully locked
2227      if(lock){
2228         //Some code
2229      }
2230      //If the mutex was locked it will be unlocked
2231   }
2232
2233[classref boost::interprocess::upgradable_lock upgradable_lock] and
2234[classref boost::interprocess::sharable_lock sharable_lock] offer
2235more features and operations, see their reference for more informations
2236
2237[important `boost::posix_time::ptime` absolute time points used by Boost.Interprocess synchronization mechanisms
2238are UTC time points, not local time points]
2239
2240[endsect]
2241
2242[/section:upgradable_mutexes_example Anonymous Upgradable Mutex Example]
2243
2244[/import ../example/comp_doc_anonymous_upgradable_mutexA.cpp]
2245[/doc_anonymous_upgradable_mutexA]
2246
2247
2248[/import ../example/comp_doc_anonymous_upgradable_mutexB.cpp]
2249[/doc_anonymous_upgradable_mutexB]
2250
2251[/endsect]
2252
2253[endsect]
2254
2255[section:lock_conversions Lock Transfers Through Move Semantics]
2256
2257[blurb [*Interprocess uses its own move semantics emulation code for compilers
2258that don't support rvalues references.
2259This is a temporary solution until a Boost move semantics library is accepted.]]
2260
2261Scoped locks and similar utilities offer simple resource management possibilities,
2262but with advanced mutex types like upgradable mutexes, there are operations where
2263an acquired lock type is released and another lock type is acquired atomically.
2264This is implemented by upgradable mutex operations like `unlock_and_lock_sharable()`.
2265
2266These operations can be managed more effectively using [*lock transfer operations].
2267A lock transfer operations explicitly indicates that a mutex owned by a lock is
2268transferred to another lock executing atomic unlocking plus locking operations.
2269
2270[section:lock_transfer_simple_transfer Simple Lock Transfer]
2271
2272Imagine that a thread modifies some data in the beginning but after that, it has to
2273just read it in a long time. The code can acquire the exclusive lock, modify the data
2274and atomically release the exclusive lock and acquire the sharable lock. With these
2275sequence we guarantee that no other thread can modify the data in the transition
2276and that more readers can acquire sharable lock, increasing concurrency.
2277Without lock transfer operations, this would be coded like this:
2278
2279[c++]
2280
2281   using boost::interprocess;
2282   interprocess_upgradable_mutex mutex;
2283
2284   //Acquire exclusive lock
2285   mutex.lock();
2286
2287   //Modify data
2288
2289   //Atomically release exclusive lock and acquire sharable lock.
2290   //More threads can acquire the sharable lock and read the data.
2291   mutex.unlock_and_lock_sharable();
2292
2293   //Read data
2294
2295   //Explicit unlocking
2296   mutex.unlock_sharable();
2297
2298
2299This can be simple, but in the presence of exceptions, it's complicated to know
2300what type of lock the mutex had when the exception was thrown and what function
2301we should call to unlock it:
2302
2303[c++]
2304
2305   try{
2306      //Mutex operations
2307   }
2308   catch(...){
2309      //What should we call? "unlock()" or "unlock_sharable()"
2310      //Is the mutex locked?
2311   }
2312
2313We can use [*lock transfer] to simplify all this management:
2314
2315[c++]
2316
2317   using boost::interprocess;
2318   interprocess_upgradable_mutex mutex;
2319
2320   //Acquire exclusive lock
2321   scoped_lock s_lock(mutex);
2322
2323   //Modify data
2324
2325   //Atomically release exclusive lock and acquire sharable lock.
2326   //More threads can acquire the sharable lock and read the data.
2327   sharable_lock(move(s_lock));
2328
2329   //Read data
2330
2331   //The lock is automatically unlocked calling the appropriate unlock
2332   //function even in the presence of exceptions.
2333   //If the mutex was not locked, no function is called.
2334
2335As we can see, even if an exception is thrown at any moment, the mutex
2336will be automatically unlocked calling the appropriate `unlock()` or
2337`unlock_sharable()` method.
2338
2339[endsect]
2340
2341[section:lock_transfer_summary Lock Transfer Summary]
2342
2343There are many lock transfer operations that we can classify according to
2344the operations presented in the upgradable mutex operations:
2345
2346* [*Guaranteed to succeed and non-blocking:] Any transition from a more
2347   restrictive lock to a less restrictive one. Scoped -> Upgradable,
2348   Scoped -> Sharable, Upgradable -> Sharable.
2349
2350* [*Not guaranteed to succeed:] The operation might succeed if no one has
2351   acquired the upgradable or exclusive lock: Sharable -> Exclusive. This
2352   operation is a try operation.
2353
2354* [*Guaranteed to succeed if using an infinite waiting:] Any transition that will succeed
2355   but needs to wait until all Sharable locks are released: Upgradable -> Scoped.
2356   Since this is a blocking operation, we can also choose not to wait infinitely
2357   and just try or wait until a timeout is reached.
2358
2359[section:lock_transfer_summary_scoped Transfers To Scoped Lock]
2360
2361Transfers to `scoped_lock` are guaranteed to succeed only from an `upgradable_lock`
2362and only if a blocking operation is requested, due to the fact that this operation
2363needs to wait until all sharable locks are released. The user can also use "try"
2364or "timed" transfer to avoid infinite locking, but succeed is not guaranteed.
2365
2366A conversion from a `sharable_lock` is never guaranteed and thus, only a try operation
2367is permitted:
2368
2369[c++]
2370
2371   //Conversions to scoped_lock
2372   {
2373      upgradable_lock<Mutex>  u_lock(mut);
2374      //This calls unlock_upgradable_and_lock()
2375      scoped_lock<Mutex>      e_lock(move(u_lock));
2376   }
2377   {
2378      upgradable_lock<Mutex>  u_lock(mut);
2379      //This calls try_unlock_upgradable_and_lock()
2380      scoped_lock<Mutex>      e_lock(move(u_lock, try_to_lock));
2381   }
2382   {
2383      boost::posix_time::ptime t = test::delay(100);
2384      upgradable_lock<Mutex>  u_lock(mut);
2385      //This calls timed_unlock_upgradable_and_lock()
2386      scoped_lock<Mutex>      e_lock(move(u_lock));
2387   }
2388   {
2389      sharable_lock<Mutex>    s_lock(mut);
2390      //This calls try_unlock_sharable_and_lock()
2391      scoped_lock<Mutex>      e_lock(move(s_lock, try_to_lock));
2392   }
2393
2394[important `boost::posix_time::ptime` absolute time points used by Boost.Interprocess synchronization mechanisms
2395are UTC time points, not local time points]
2396
2397[endsect]
2398
2399[section:lock_transfer_summary_upgradable Transfers To Upgradable Lock]
2400
2401A transfer to an `upgradable_lock` is guaranteed to succeed only from a `scoped_lock`
2402since scoped locking is a more restrictive locking than an upgradable locking. This
2403operation is also non-blocking.
2404
2405A transfer from a `sharable_lock` is not guaranteed and only a "try" operation is permitted:
2406
2407[c++]
2408
2409   //Conversions to upgradable
2410   {
2411      sharable_lock<Mutex>    s_lock(mut);
2412      //This calls try_unlock_sharable_and_lock_upgradable()
2413      upgradable_lock<Mutex>  u_lock(move(s_lock, try_to_lock));
2414   }
2415   {
2416      scoped_lock<Mutex>      e_lock(mut);
2417      //This calls unlock_and_lock_upgradable()
2418      upgradable_lock<Mutex>  u_lock(move(e_lock));
2419   }
2420
2421[endsect]
2422
2423[section:lock_transfer_summary_sharable Transfers To Sharable Lock]
2424
2425All transfers to a `sharable_lock` are guaranteed to succeed since both
2426`upgradable_lock` and `scoped_lock` are more restrictive than `sharable_lock`.
2427These operations are also non-blocking:
2428
2429[c++]
2430
2431   //Conversions to sharable_lock
2432   {
2433      upgradable_lock<Mutex>  u_lock(mut);
2434      //This calls unlock_upgradable_and_lock_sharable()
2435      sharable_lock<Mutex>    s_lock(move(u_lock));
2436   }
2437   {
2438      scoped_lock<Mutex>      e_lock(mut);
2439      //This calls unlock_and_lock_sharable()
2440      sharable_lock<Mutex>    s_lock(move(e_lock));
2441   }
2442
2443[endsect]
2444
2445[endsect]
2446
2447[section:lock_transfer_not_locked Transferring Unlocked Locks]
2448
2449In the previous examples, the mutex used in the transfer operation was previously
2450locked:
2451
2452[c++]
2453
2454      Mutex mut;
2455
2456      //This calls mut.lock()
2457      scoped_lock<Mutex>      e_lock(mut);
2458
2459      //This calls unlock_and_lock_sharable()
2460      sharable_lock<Mutex>    s_lock(move(e_lock));
2461   }
2462
2463but it's possible to execute the transfer with an unlocked source, due to explicit
2464unlocking, a try, timed or a `defer_lock` constructor:
2465
2466[c++]
2467
2468   //These operations can leave the mutex unlocked!
2469
2470   {
2471      //Try might fail
2472      scoped_lock<Mutex>      e_lock(mut, try_to_lock);
2473      sharable_lock<Mutex>    s_lock(move(e_lock));
2474   }
2475   {
2476      //Timed operation might fail
2477      scoped_lock<Mutex>      e_lock(mut, time);
2478      sharable_lock<Mutex>    s_lock(move(e_lock));
2479   }
2480   {
2481      //Avoid mutex locking
2482      scoped_lock<Mutex>      e_lock(mut, defer_lock);
2483      sharable_lock<Mutex>    s_lock(move(e_lock));
2484   }
2485   {
2486      //Explicitly call unlock
2487      scoped_lock<Mutex>      e_lock(mut);
2488      e_lock.unlock();
2489      //Mutex was explicitly unlocked
2490      sharable_lock<Mutex>    s_lock(move(e_lock));
2491   }
2492
2493If the source mutex was not locked:
2494
2495* The target lock does not execute the atomic `unlock_xxx_and_lock_xxx` operation.
2496* The target lock is also unlocked.
2497* The source lock is released() and the ownership of the mutex is transferred to the target.
2498
2499[c++]
2500
2501   {
2502      scoped_lock<Mutex>      e_lock(mut, defer_lock);
2503      sharable_lock<Mutex>    s_lock(move(e_lock));
2504
2505      //Assertions
2506      assert(e_lock.mutex() == 0);
2507      assert(s_lock.mutex() != 0);
2508      assert(e_lock.owns()  == false);
2509   }
2510
2511[endsect]
2512
2513[section:lock_transfer_failure Transfer Failures]
2514
2515When executing a lock transfer, the operation can fail:
2516
2517* The executed atomic mutex unlock plus lock function might throw.
2518* The executed atomic function might be a "try" or "timed" function that can fail.
2519
2520In the first case, the mutex ownership is not transferred and the source lock's
2521destructor will unlock the mutex:
2522
2523[c++]
2524
2525   {
2526      scoped_lock<Mutex>      e_lock(mut, defer_lock);
2527
2528      //This operations throws because
2529      //"unlock_and_lock_sharable()" throws!!!
2530      sharable_lock<Mutex>    s_lock(move(e_lock));
2531
2532      //Some code ...
2533
2534      //e_lock's destructor will call "unlock()"
2535   }
2536
2537In the second case, if an internal "try" or "timed" operation fails (returns "false")
2538then the mutex ownership is [*not] transferred, the source lock is unchanged and the target
2539lock's state will the same as a default construction:
2540
2541[c++]
2542
2543   {
2544      sharable_lock<Mutex>    s_lock(mut);
2545
2546      //Internal "try_unlock_sharable_and_lock_upgradable()" returns false
2547      upgradable_lock<Mutex>  u_lock(move(s_lock, try_to_lock));
2548
2549      assert(s_lock.mutex() == &mut);
2550      assert(s_lock.owns()  == true);
2551      assert(u_lock.mutex() == 0);
2552      assert(u_lock.owns()  == false);
2553
2554      //u_lock's destructor does nothing
2555      //s_lock's destructor calls "unlock()"
2556   }
2557
2558[endsect]
2559
2560[endsect]
2561
2562[section:file_lock File Locks]
2563
2564[section:file_lock_whats_a_file_lock What's A File Lock?]
2565
2566A file lock is an interprocess synchronization mechanism to protect concurrent
2567writes and reads to files using a mutex ['embedded] in the file. This ['embedded mutex]
2568has sharable and exclusive locking capabilities.
2569With a file lock, an existing file can be used as a mutex without the need
2570of creating additional synchronization objects to control concurrent file
2571reads or writes.
2572
2573Generally speaking, we can have two file locking capabilities:
2574
2575*  [*Advisory locking:] The operating system kernel maintains a list of files that
2576   have been locked. But does not prevent writing to those files even if a process
2577   has acquired a sharable lock or does not prevent reading from the file when a process
2578   has acquired the exclusive lock. Any process can ignore an advisory lock.
2579   This means that advisory locks are for [*cooperating] processes,
2580   processes that can trust each other. This is similar to a mutex protecting data
2581   in a shared memory segment: any process connected to that memory can overwrite the
2582   data but [*cooperative] processes use mutexes to protect the data first acquiring
2583   the mutex lock.
2584
2585*  [*Mandatory locking:] The OS kernel checks every read and write request to verify
2586   that the operation can be performed according to the acquired lock. Reads and writes
2587   block until the lock is released.
2588
2589[*Boost.Interprocess] implements [*advisory blocking] because of portability reasons.
2590This means that every process accessing to a file concurrently, must cooperate using
2591file locks to synchronize the access.
2592
2593In some systems file locking can be even further refined, leading to [*record locking],
2594where a user can specify a [*byte range] within the file where the lock is applied.
2595This allows concurrent write access by several processes if they need to access a
2596different byte range in the file. [*Boost.Interprocess] does [*not] offer record
2597locking for the moment, but might offer it in the future. To use a file lock just
2598include:
2599
2600[c++]
2601
2602   #include <boost/interprocess/sync/file_lock.hpp>
2603
2604A file locking is a class that has [*process lifetime]. This means that if a process
2605holding a file lock ends or crashes, the operating system will automatically unlock
2606it. This feature is very useful in some situations where we want to assure
2607automatic unlocking even when the process crashes and avoid leaving blocked resources
2608in the system. A file lock is constructed using the name of the file as an argument:
2609
2610[c++]
2611
2612   #include <boost/interprocess/sync/file_lock.hpp>
2613
2614   int main()
2615   {
2616      //This throws if the file does not exist or it can't
2617      //open it with read-write access!
2618      boost::interprocess::file_lock flock("my_file");
2619      return 0;
2620   }
2621
2622
2623[endsect]
2624
2625[section:file_lock_operations File Locking Operations]
2626
2627File locking has normal mutex operations plus sharable locking capabilities.
2628This means that we can have multiple readers holding the sharable lock and
2629writers holding the exclusive lock waiting until the readers end their job.
2630
2631However, file locking does [*not] support upgradable locking or promotion or
2632demotion (lock transfers), so it's more limited than an upgradable lock.
2633These are the operations:
2634
2635[blurb ['[*void lock()]]]
2636
2637[*Effects:]
2638The calling thread tries to obtain exclusive ownership of the file lock, and if
2639another thread has exclusive or sharable ownership of the mutex,
2640it waits until it can obtain the ownership.
2641
2642[*Throws:] *interprocess_exception* on error.
2643
2644[blurb ['[*bool try_lock()]]]
2645
2646[*Effects:]
2647The calling thread tries to acquire exclusive ownership of the file lock
2648without waiting. If no other thread has exclusive or sharable ownership of
2649the file lock, this succeeds.
2650
2651[*Returns:] If it can acquire exclusive ownership immediately returns true.
2652If it has to wait, returns false.
2653
2654[*Throws:] *interprocess_exception* on error.
2655
2656[blurb ['[*bool timed_lock(const boost::posix_time::ptime &abs_time)]]]
2657
2658[*Effects:]
2659The calling thread tries to acquire exclusive ownership of the file lock
2660waiting if necessary until no other thread has exclusive or
2661sharable ownership of the file lock or abs_time is reached.
2662
2663[*Returns:] If acquires exclusive ownership, returns true. Otherwise
2664returns false.
2665
2666[*Throws:] *interprocess_exception* on error.
2667
2668[blurb ['[*void unlock()]]]
2669
2670[*Precondition:] The thread must have exclusive ownership of the file lock.
2671
2672[*Effects:] The calling thread releases the exclusive ownership of the file lock.
2673
2674[*Throws:] An exception derived from *interprocess_exception* on error.
2675
2676[blurb ['[*void lock_sharable()]]]
2677
2678[*Effects:]
2679The calling thread tries to obtain sharable ownership of the file lock,
2680and if another thread has exclusive ownership of the file lock,
2681waits until it can obtain the ownership.
2682
2683[*Throws:] *interprocess_exception* on error.
2684
2685[blurb ['[*bool try_lock_sharable()]]]
2686
2687[*Effects:]
2688The calling thread tries to acquire sharable ownership of the file
2689lock without waiting. If no other thread has exclusive ownership of
2690the file lock, this succeeds.
2691
2692[*Returns:] If it can acquire sharable ownership immediately returns true.
2693If it has to wait, returns false.
2694
2695[*Throws:] *interprocess_exception* on error.
2696
2697[blurb ['[*bool timed_lock_sharable(const boost::posix_time::ptime &abs_time)]]]
2698
2699[*Effects:]
2700The calling thread tries to acquire sharable ownership of the file lock
2701waiting if necessary until no other thread has exclusive
2702ownership of the file lock or abs_time is reached.
2703
2704[*Returns:] If acquires sharable ownership, returns true. Otherwise
2705returns false.
2706
2707[*Throws:] *interprocess_exception* on error.
2708
2709[blurb ['[*void unlock_sharable()]]]
2710
2711[*Precondition:] The thread must have sharable ownership of the file lock.
2712
2713[*Effects:] The calling thread releases the sharable ownership of the file lock.
2714
2715[*Throws:] An exception derived from *interprocess_exception* on error.
2716
2717For more file locking methods, please
2718[classref boost::interprocess::file_lock file_lock reference].
2719
2720[important `boost::posix_time::ptime` absolute time points used by Boost.Interprocess synchronization mechanisms
2721are UTC time points, not local time points]
2722
2723[endsect]
2724
2725[section:file_lock_scoped_locks Scoped Lock and Sharable Lock With File Locking]
2726
2727[classref boost::interprocess::scoped_lock scoped_lock] and
2728[classref boost::interprocess::sharable_lock sharable_lock] can be used to make
2729file locking easier in the presence of exceptions, just like with mutexes:
2730
2731[c++]
2732
2733   #include <boost/interprocess/sync/file_lock.hpp>
2734   #include <boost/interprocess/sync/sharable_lock.hpp>
2735   //...
2736
2737   using namespace boost::interprocess;
2738   //This process reads the file
2739   //    ...
2740   //Open the file lock
2741   file_lock f_lock("my_file");
2742
2743   {
2744      //Construct a sharable lock with the file lock.
2745      //This will call "f_lock.sharable_lock()".
2746      sharable_lock<file_lock> sh_lock(f_lock);
2747
2748      //Now read the file...
2749
2750      //The sharable lock is automatically released by
2751      //sh_lock's destructor
2752   }
2753
2754[c++]
2755
2756   #include <boost/interprocess/sync/file_lock.hpp>
2757   #include <boost/interprocess/sync/scoped_lock.hpp>
2758
2759   //...
2760
2761   using namespace boost::interprocess;
2762   //This process writes the file
2763   //    ...
2764   //Open the file lock
2765   file_lock f_lock("my_file");
2766
2767   {
2768      //Construct an exclusive lock with the file lock.
2769      //This will call "f_lock.lock()".
2770      scoped_lock<file_lock> e_lock(f_lock);
2771
2772      //Now write the file...
2773
2774      //The exclusive lock is automatically released by
2775      //e_lock's destructor
2776   }
2777
2778However, lock transfers are only allowed between same type of locks, that is,
2779from a sharable lock to another sharable lock or from a scoped lock to another
2780scoped lock.  A transfer from a scoped lock to a sharable lock is not allowed,
2781because [classref boost::interprocess::file_lock file_lock] has no lock
2782promotion or demotion functions like `unlock_and_lock_sharable()`.
2783This will produce a compilation error:
2784
2785[c++]
2786
2787   //Open the file lock
2788   file_lock f_lock("my_file");
2789
2790   scoped_lock<file_lock> e_lock(f_lock);
2791
2792   //Compilation error, f_lock has no "unlock_and_lock_sharable()" member!
2793   sharable_lock<file_lock> e_lock(move(f_lock));
2794
2795
2796[endsect]
2797
2798[section:file_lock_not_thread_safe Caution: Synchronization limitations]
2799
2800If you plan to use file locks just like named mutexes, be careful, because portable
2801file locks have synchronization limitations, mainly because different implementations
2802(POSIX, Windows) offer different guarantees. Interprocess file locks have the following
2803limitations:
2804
2805*  It's unspecified if a `file_lock` synchronizes [*two threads from the same process].
2806*  It's unspecified if a process can use two `file_lock` objects pointing to the same file.
2807
2808The first limitation comes mainly from POSIX, since a file handle is a per-process attribute
2809and not a per-thread attribute. This means that if a thread uses a `file_lock` object to lock
2810a file, other threads will see the file as locked.
2811Windows file locking mechanism, on the other hand, offer thread-synchronization guarantees
2812so a thread trying to lock the already locked file, would block.
2813
2814The second limitation comes from the fact that file locking synchronization state
2815is tied with a single file descriptor in Windows. This means that if two `file_lock`
2816objects are created pointing to the same file, no synchronization is guaranteed. In
2817POSIX, when two file descriptors are used to lock a file if a descriptor is closed,
2818all file locks set by the calling process are cleared.
2819
2820To sum up, if you plan to use portable file locking in your processes, use the following
2821restrictions:
2822
2823*  [*For each file, use a single `file_lock` object per process.]
2824*  [*Use the same thread to lock and unlock a file.]
2825*  If you are using a std::fstream/native file handle to write to the file
2826      while using file locks on that file, [*don't close the file before
2827      releasing all the locks of the file.]
2828
2829[endsect]
2830
2831[section:file_lock_careful_iostream Be Careful With Iostream Writing]
2832
2833As we've seen file locking can be useful to synchronize two processes,
2834but [*make sure data is written to the file]
2835before unlocking the file lock. Take in care that iostream classes do some
2836kind of buffering, so if you want to make sure that other processes can
2837see the data you've written, you have the following alternatives:
2838
2839*  Use native file functions (read()/write() in Unix systems and ReadFile/WriteFile
2840   in Windows systems) instead of iostream.
2841
2842*  Flush data before unlocking the file lock in writers using `fflush` if you are using
2843   standard C functions or the `flush()` member function when using C++ iostreams. In windows
2844   you can't even use another class to access the same file.
2845
2846   //...
2847
2848   using namespace boost::interprocess;
2849   //This process writes the file
2850   //    ...
2851   //Open the file lock
2852   fstream file("my_file")
2853   file_lock f_lock("my_lock_file");
2854
2855   {
2856      scoped_lock<file_lock> e_lock(f_lock);
2857
2858      //Now write the file...
2859
2860      //Flush data before unlocking the exclusive lock
2861      file.flush();
2862   }
2863
2864[endsect]
2865
2866[endsect]
2867
2868[section:message_queue Message Queue]
2869
2870[section:message_queue_whats_a_mq What's A Message Queue?]
2871
2872A message queue is similar to a list of messages. Threads can put messages
2873in the queue and they can also remove messages from the queue. Each message
2874can have also a [*priority] so that higher priority messages are read before
2875lower priority messages. Each message has some attributes:
2876
2877* A priority.
2878* The length of the message.
2879* The data (if length is bigger than 0).
2880
2881A thread can send a message to or receive a message from the message
2882queue using 3 methods:
2883
2884* [*Blocking]: If the message queue is full when sending or the message queue
2885   is empty when receiving, the thread is blocked until there
2886   is room for a new message or there is a new message.
2887* [*Try]: If the message queue is full when sending or the message queue is empty
2888   when receiving, the thread returns immediately with an error.
2889* [*Timed]: If the message queue is full when sending or the message queue is empty
2890   when receiving, the thread retries the operation until succeeds (returning
2891   successful state) or a timeout is reached (returning a failure).
2892
2893A message queue [*just copies raw bytes between processes] and does not send
2894objects. This means that if we want to send an object using a message queue
2895[*the object must be binary serializable]. For example, we can send integers
2896between processes but [*not] a `std::string`. You should use [*Boost.Serialization]
2897or use advanced [*Boost.Interprocess] mechanisms to send complex data between
2898processes.
2899
2900The [*Boost.Interprocess] message queue is a named interprocess communication: the
2901message queue is created with a name and it's opened with a name, just like a file.
2902When creating a message queue, the user must specify the maximum message size and
2903the maximum message number that the message queue can store. These parameters will
2904define the resources (for example the size of the shared memory used to implement
2905the message queue if shared memory is used).
2906
2907[c++]
2908
2909   using boost::interprocess;
2910   //Create a message_queue. If the queue
2911   //exists throws an exception
2912   message_queue mq
2913      (create_only         //only create
2914      ,"message_queue"     //name
2915      ,100                 //max message number
2916      ,100                 //max message size
2917      );
2918
2919[c++]
2920
2921   using boost::interprocess;
2922   //Creates or opens a message_queue. If the queue
2923   //does not exist creates it, otherwise opens it.
2924   //Message number and size are ignored if the queue
2925   //is opened
2926   message_queue mq
2927      (open_or_create      //open or create
2928      ,"message_queue"     //name
2929      ,100                 //max message number
2930      ,100                 //max message size
2931      );
2932
2933[c++]
2934
2935   using boost::interprocess;
2936   //Opens a message_queue. If the queue
2937   //does not exist throws an exception.
2938   message_queue mq
2939      (open_only           //only open
2940      ,"message_queue"     //name
2941      );
2942
2943The message queue is explicitly removed calling the static `remove` function:
2944
2945[c++]
2946
2947   using boost::interprocess;
2948   message_queue::remove("message_queue");
2949
2950The function can fail if the message queue is still being used by any process.
2951
2952[endsect]
2953
2954[section:message_queue_example Using a message queue]
2955
2956To use a message queue you must include the following header:
2957
2958[c++]
2959
2960   #include <boost/interprocess/ipc/message_queue.hpp>
2961
2962In the following example, the first process creates the message queue, and writes
2963an array of integers on it. The other process just reads the array and checks that
2964the sequence number is correct. This is the first process:
2965
2966[import ../example/comp_doc_message_queueA.cpp]
2967[doc_message_queueA]
2968
2969This is the second process:
2970
2971[import ../example/comp_doc_message_queueB.cpp]
2972[doc_message_queueB]
2973
2974To know more about this class and all its operations, please see the
2975[classref boost::interprocess::message_queue message_queue] class reference.
2976
2977[endsect]
2978
2979[endsect]
2980
2981[endsect]
2982
2983[section:managed_memory_segments Managed Memory Segments]
2984
2985[section:making_ipc_easy Making Interprocess Data Communication Easy]
2986
2987[section:managed_memory_segments_intro Introduction]
2988
2989As we have seen, [*Boost.Interprocess] offers some basic classes to create shared memory
2990objects and file mappings and map those mappable classes to the process' address space.
2991
2992However, managing those memory segments is not not easy for non-trivial tasks.
2993A mapped region is a fixed-length memory buffer and creating and destroying objects
2994of any type dynamically, requires a lot of work, since it would require programming
2995a memory management algorithm to allocate portions of that segment.
2996Many times, we also want to associate names to objects created in shared memory, so
2997all the processes can find the object using the name.
2998
2999[*Boost.Interprocess] offers 4 managed memory segment classes:
3000
3001*  To manage a shared memory mapped region ([*basic_managed_shared_memory] class).
3002*  To manage a memory mapped file ([*basic_managed_mapped_file]).
3003*  To manage a heap allocated (`operator new`) memory buffer ([*basic_managed_heap_memory] class).
3004*  To manage a user provided fixed size buffer ([*basic_managed_external_buffer] class).
3005
3006The first two classes manage memory segments that can be shared between processes. The
3007third is useful to create complex data-bases to be sent though other mechanisms like
3008message queues to other processes. The fourth class can manage any fixed size memory
3009buffer. The first two classes will be explained in the next two sections.
3010[*basic_managed_heap_memory] and [*basic_managed_external_buffer] will be explained later.
3011
3012The most important services of a managed memory segment are:
3013
3014*  Dynamic allocation of portions of a memory the segment.
3015*  Construction of C++ objects in the memory segment. These objects can be anonymous
3016   or we can associate a name to them.
3017*  Searching capabilities for named objects.
3018*  Customization of many features: memory allocation algorithm, index types or
3019   character types.
3020*  Atomic constructions and destructions so that if the segment is shared between
3021   two processes it's impossible to create two objects associated with the same
3022   name, simplifying synchronization.
3023
3024[endsect]
3025
3026[section:managed_memory_segment_int Declaration of managed memory segment classes]
3027
3028All [*Boost.Interprocess] managed memory segment classes are templatized classes
3029that can be customized by the user:
3030
3031[c++]
3032
3033   template
3034         <
3035            class CharType,
3036            class MemoryAlgorithm,
3037            template<class IndexConfig> class IndexType
3038         >
3039   class basic_managed_shared_memory / basic_managed_mapped_file /
3040         basic_managed_heap_memory   / basic_external_buffer;
3041
3042These classes can be customized with the following template parameters:
3043
3044*  *CharType* is the type of the character that will be used to identify
3045   the created named objects (for example, *char* or *wchar_t*)
3046
3047*  *MemoryAlgorithm* is the memory algorithm used to allocate portions of the
3048   segment (for example, rbtree_best_fit ). The internal typedefs of the
3049   memory algorithm also define:
3050   *  The synchronization type (`MemoryAlgorithm::mutex_family`) to be used
3051      in all allocation operations.
3052      This allows the use of user-defined mutexes or avoiding internal
3053      locking (maybe code will be externally synchronized by the user).
3054
3055   *  The Pointer type (`MemoryAlgorithm::void_pointer`) to be used
3056      by the memory allocation algorithm or additional helper structures
3057      (like a map to maintain object/name associations). All STL compatible
3058      allocators and containers to be used with this managed memory segment
3059      will use this pointer type. The pointer type
3060      will define if the managed memory segment can be mapped between
3061      several processes. For example, if `void_pointer` is `offset_ptr<void>`
3062      we will be able to map the managed segment in different base
3063      addresses in each process. If `void_pointer` is `void*` only fixed
3064      address mapping could be used.
3065
3066   *  See [link interprocess.customizing_interprocess.custom_interprocess_alloc Writing a new memory
3067      allocation algorithm] for more details about memory algorithms.
3068
3069*  *IndexType* is the type of index that will be used to store the name-object
3070   association (for example, a map, a hash-map, or an ordered vector).
3071
3072This way, we can use `char` or `wchar_t` strings to identify created C++
3073objects in the memory segment, we can plug new shared memory allocation
3074algorithms, and use the index type that is best suited to our needs.
3075
3076[endsect]
3077
3078[endsect]
3079
3080[section:managed_shared_memory Managed Shared Memory]
3081
3082[section:managed_memory_common_shm Common Managed Shared Memory Classes]
3083
3084As seen, *basic_managed_shared_memory* offers a great variety of customization. But
3085for the average user, a common, default shared memory named object creation is needed.
3086Because of this, [*Boost.Interprocess] defines the most common managed shared memory
3087specializations:
3088
3089[c++]
3090
3091   //!Defines a managed shared memory with c-strings as keys for named objects,
3092   //!the default memory algorithm (with process-shared mutexes,
3093   //!and offset_ptr as internal pointers) as memory allocation algorithm
3094   //!and the default index type as the index.
3095   //!This class allows the shared memory to be mapped in different base
3096   //!in different processes
3097   typedef
3098      basic_managed_shared_memory<char
3099                                 ,/*Default memory algorithm defining offset_ptr<void> as void_pointer*/
3100                                 ,/*Default index type*/>
3101      managed_shared_memory;
3102
3103   //!Defines a managed shared memory with wide strings as keys for named objects,
3104   //!the default memory algorithm (with process-shared mutexes,
3105   //!and offset_ptr as internal pointers) as memory allocation algorithm
3106   //!and the default index type as the index.
3107   //!This class allows the shared memory to be mapped in different base
3108   //!in different processes
3109   typedef
3110      basic_managed_shared_memory<wchar_t
3111                                 ,/*Default memory algorithm defining offset_ptr<void> as void_pointer*/
3112                                 ,/*Default index type*/>
3113      wmanaged_shared_memory;
3114
3115`managed_shared_memory` allocates objects in shared memory associated with a c-string and
3116`wmanaged_shared_memory` allocates objects in shared memory associated with a wchar_t null
3117terminated string. Both define the pointer type as `offset_ptr<void>` so they can be
3118used to map the shared memory at different base addresses in different processes.
3119
3120If the user wants to map the shared memory in the same address in all processes and
3121want to use raw pointers internally instead of offset pointers, [*Boost.Interprocess]
3122defines the following types:
3123
3124[c++]
3125
3126   //!Defines a managed shared memory with c-strings as keys for named objects,
3127   //!the default memory algorithm (with process-shared mutexes,
3128   //!and offset_ptr as internal pointers) as memory allocation algorithm
3129   //!and the default index type as the index.
3130   //!This class allows the shared memory to be mapped in different base
3131   //!in different processes*/
3132   typedef basic_managed_shared_memory
3133      <char
3134      ,/*Default memory algorithm defining void * as void_pointer*/
3135      ,/*Default index type*/>
3136   fixed_managed_shared_memory;
3137
3138   //!Defines a managed shared memory with wide strings as keys for named objects,
3139   //!the default memory algorithm (with process-shared mutexes,
3140   //!and offset_ptr as internal pointers) as memory allocation algorithm
3141   //!and the default index type as the index.
3142   //!This class allows the shared memory to be mapped in different base
3143   //!in different processes
3144   typedef basic_managed_shared_memory
3145      <wchar_t
3146      ,/*Default memory algorithm defining void * as void_pointer*/
3147      ,/*Default index type*/>
3148   wfixed_managed_shared_memory;
3149
3150[endsect]
3151
3152[section:constructing_managed_shared_memories Constructing Managed Shared Memory]
3153
3154Managed shared memory is an advanced class that combines a shared memory object
3155and a mapped region that covers all the shared memory object. That means that
3156when we [*create] a new managed shared memory:
3157
3158*  A new shared memory object is created.
3159*  The whole shared memory object is mapped in the process' address space.
3160*  Some helper objects are constructed (name-object index, internal synchronization
3161   objects, internal variables...) in the mapped region to implement
3162   managed memory segment features.
3163
3164When we [*open] a managed shared memory
3165
3166*  A shared memory object is opened.
3167*  The whole shared memory object is mapped in the process' address space.
3168
3169To use a managed shared memory, you must include the following header:
3170
3171[c++]
3172
3173   #include <boost/interprocess/managed_shared_memory.hpp>
3174
3175
3176[c++]
3177
3178   //1.  Creates a new shared memory object
3179   //    called "MySharedMemory".
3180   //2.  Maps the whole object to this
3181   //    process' address space.
3182   //3.  Constructs some objects in shared memory
3183   //    to implement managed features.
3184   //!!  If anything fails, throws interprocess_exception
3185   //
3186   managed_shared_memory segment      ( create_only
3187                                      , "MySharedMemory" //Shared memory object name
3188                                      , 65536);          //Shared memory object size in bytes
3189
3190
3191[c++]
3192
3193   //1.  Opens a shared memory object
3194   //    called "MySharedMemory".
3195   //2.  Maps the whole object to this
3196   //    process' address space.
3197   //3.  Obtains pointers to constructed internal objects
3198   //    to implement managed features.
3199   //!!  If anything fails, throws interprocess_exception
3200   //
3201   managed_shared_memory segment      (open_only,       "MySharedMemory");//Shared memory object name
3202
3203
3204[c++]
3205
3206   //1.  If the segment was previously created
3207   //    equivalent to "open_only" (size is ignored).
3208   //2.  Otherwise, equivalent to "create_only"
3209   //!!  If anything fails, throws interprocess_exception
3210   //
3211   managed_shared_memory segment      ( open_or_create
3212                                      , "MySharedMemory" //Shared memory object name
3213                                      , 65536);          //Shared memory object size in bytes
3214
3215
3216When the `managed_shared_memory` object is destroyed, the shared memory
3217object is automatically unmapped, and all the resources are freed. To remove
3218the shared memory object from the system you must use the `shared_memory_object::remove`
3219function. Shared memory object removing might fail if any
3220process still has the shared memory object mapped.
3221
3222The user can also map the managed shared memory in a fixed address. This option is
3223essential when using using `fixed_managed_shared_memory`. To do this, just
3224add the mapping address as an extra parameter:
3225
3226[c++]
3227
3228   fixed_managed_shared_memory segment      (open_only      ,"MyFixedAddressSharedMemory" //Shared memory object name
3229      ,(void*)0x30000000            //Mapping address
3230
3231[endsect]
3232
3233[section:windows_managed_memory_common_shm Using native windows shared memory]
3234
3235Windows users might also want to use native windows shared memory instead of
3236the portable [classref boost::interprocess::shared_memory_object shared_memory_object]
3237managed memory. This is achieved through the
3238[classref boost::interprocess::basic_managed_windows_shared_memory basic_managed_windows_shared_memory]
3239class. To use it just include:
3240
3241[c++]
3242
3243   #include <boost/interprocess/managed_windows_shared_memory.hpp>
3244
3245This class has the same interface as
3246[classref boost::interprocess::basic_managed_shared_memory basic_managed_shared_memory]
3247but uses native windows shared memory. Note that this managed class has the same
3248lifetime issues as the windows shared memory: when the last process attached to the
3249windows shared memory is detached from the memory (or ends/crashes) the memory is
3250destroyed. So there is no persistence support for windows shared memory.
3251
3252To communicate between system services and user applications using `managed_windows_shared_memory`,
3253please read the explanations given in chapter
3254[link interprocess.sharedmemorybetweenprocesses.sharedmemory.windows_shared_memory Native windows shared memory].
3255
3256[endsect]
3257
3258[section:xsi_managed_memory_common_shm Using XSI (system V) shared memory]
3259
3260Unix users might also want to use XSI (system V) instead of
3261the portable [classref boost::interprocess::shared_memory_object shared_memory_object]
3262managed memory. This is achieved through the
3263[classref boost::interprocess::basic_managed_xsi_shared_memory basic_managed_xsi_shared_memory]
3264class. To use it just include:
3265
3266[c++]
3267
3268   #include <boost/interprocess/managed_xsi_shared_memory.hpp>
3269
3270This class has nearly the same interface as
3271[classref boost::interprocess::basic_managed_shared_memory basic_managed_shared_memory]
3272but uses XSI shared memory as backend.
3273
3274[endsect]
3275
3276For more information about managed XSI shared memory capabilities, see
3277[classref boost::interprocess::basic_managed_xsi_shared_memory basic_managed_xsi_shared_memory] class reference.
3278
3279[endsect]
3280
3281[section:managed_mapped_files Managed Mapped File]
3282
3283[section:managed_memory_common_mfile Common Managed Mapped Files]
3284
3285As seen, *basic_managed_mapped_file* offers a great variety of customization. But
3286for the average user, a common, default shared memory named object creation is needed.
3287Because of this, [*Boost.Interprocess] defines the most common managed mapped file
3288specializations:
3289
3290[c++]
3291
3292   //Named object creation managed memory segment
3293   //All objects are constructed in the memory-mapped file
3294   //   Names are c-strings,
3295   //   Default memory management algorithm(rbtree_best_fit with no mutexes)
3296   //   Name-object mappings are stored in the default index type (flat_map)
3297   typedef basic_managed_mapped_file <
3298      char,
3299      rbtree_best_fit<mutex_family, offset_ptr<void> >,
3300      flat_map_index
3301      >  managed_mapped_file;
3302
3303   //Named object creation managed memory segment
3304   //All objects are constructed in the memory-mapped file
3305   //   Names are wide-strings,
3306   //   Default memory management algorithm(rbtree_best_fit with no mutexes)
3307   //   Name-object mappings are stored in the default index type (flat_map)
3308   typedef basic_managed_mapped_file<
3309      wchar_t,
3310      rbtree_best_fit<mutex_family, offset_ptr<void> >,
3311      flat_map_index
3312      >  wmanaged_mapped_file;
3313
3314`managed_mapped_file` allocates objects in a memory mapped files associated with a c-string
3315and `wmanaged_mapped_file` allocates objects in a memory mapped file associated with a wchar_t null
3316terminated string. Both define the pointer type as `offset_ptr<void>` so they can be
3317used to map the file at different base addresses in different processes.
3318
3319[endsect]
3320
3321[section:constructing_managed_mapped_files Constructing Managed Mapped Files]
3322
3323Managed mapped file is an advanced class that combines a file
3324and a mapped region that covers all the file.  That means that
3325when we [*create] a new managed mapped file:
3326
3327*  A new file is created.
3328*  The whole file is mapped in the process' address space.
3329*  Some helper objects are constructed (name-object index, internal synchronization
3330   objects, internal variables...) in the mapped region to implement
3331   managed memory segment features.
3332
3333When we [*open] a managed mapped file
3334
3335*  A file is opened.
3336*  The whole file is mapped in the process' address space.
3337
3338To use a managed mapped file, you must include the following header:
3339
3340[c++]
3341
3342   #include <boost/interprocess/managed_mapped_file.hpp>
3343
3344[c++]
3345
3346   //1.  Creates a new file
3347   //    called "MyMappedFile".
3348   //2.  Maps the whole file to this
3349   //    process' address space.
3350   //3.  Constructs some objects in the memory mapped
3351   //    file to implement managed features.
3352   //!!  If anything fails, throws interprocess_exception
3353   //
3354   managed_mapped_file mfile      ( create_only
3355                                  , "MyMappedFile" //Mapped file name
3356                                  , 65536);        //Mapped file size
3357[c++]
3358
3359   //1.  Opens a file
3360   //    called "MyMappedFile".
3361   //2.  Maps the whole file to this
3362   //    process' address space.
3363   //3.  Obtains pointers to constructed internal objects
3364   //    to implement managed features.
3365   //!!  If anything fails, throws interprocess_exception
3366   //
3367   managed_mapped_file mfile      ( open_only
3368                                  , "MyMappedFile"); //Mapped file name
3369
3370[c++]
3371
3372   //1.  If the file was previously created
3373   //    equivalent to "open_only".
3374   //2.  Otherwise, equivalent to "open_only" (size is ignored)
3375   //
3376   //!!  If anything fails, throws interprocess_exception
3377   //
3378   managed_mapped_file mfile      (open_or_create
3379                                  , "MyMappedFile" //Mapped file name
3380                                  , 65536);        //Mapped file size
3381
3382When the `managed_mapped_file` object is destroyed, the file is
3383automatically unmapped, and all the resources are freed. To remove
3384the file from the filesystem you could use standard C `std::remove`
3385or [*Boost.Filesystem]'s `remove()` functions, but file removing might fail
3386if any process still has the file mapped in memory or the file is open
3387by any process.
3388
3389To obtain a more portable behaviour, use `file_mapping::remove(const char *)` operation, which
3390will remove the file even if it's being mapped. However, removal will fail in some OS systems if
3391the file (eg. by C++ file streams) and no delete share permission was granted to the file. But in
3392most common cases `file_mapping::remove` is portable enough.
3393
3394[endsect]
3395
3396For more information about managed mapped file capabilities, see
3397[classref boost::interprocess::basic_managed_mapped_file basic_managed_mapped_file] class reference.
3398
3399[endsect]
3400
3401[section:managed_memory_segment_features Managed Memory Segment Features]
3402
3403The following features are common to all managed memory segment classes, but
3404we will use managed shared memory in our examples. We can do the same with
3405memory mapped files or other managed memory segment classes.
3406
3407[section:allocate_deallocate Allocating fragments of a managed memory segment]
3408
3409If a basic raw-byte allocation is needed from a managed memory
3410segment, (for example, a managed shared memory), to implement
3411top-level interprocess communications, this class offers
3412[*allocate] and [*deallocate] functions. The allocation function
3413comes with throwing and no throwing versions. Throwing version throws
3414boost::interprocess::bad_alloc (which derives from `std::bad_alloc`)
3415if there is no more memory and the non-throwing version returns 0 pointer.
3416
3417[import ../example/doc_managed_raw_allocation.cpp]
3418[doc_managed_raw_allocation]
3419
3420[endsect]
3421
3422[section:segment_offset Obtaining handles to identify data]
3423
3424The class also offers conversions between absolute addresses that belong to
3425a managed memory segment and a handle that can be passed using any
3426interprocess mechanism. That handle can be transformed again to an absolute
3427address using a managed memory segment that also contains that object.
3428Handles can be used as keys between processes to identify allocated portions
3429of a managed memory segment or objects constructed in the managed segment.
3430
3431[c++]
3432
3433   //Process A obtains the offset of the address
3434   managed_shared_memory::handle handle =
3435      segment.get_handle_from_address(processA_address);
3436
3437   //Process A sends this address using any mechanism to process B
3438
3439   //Process B obtains the handle and transforms it again to an address
3440   managed_shared_memory::handle handle = ...
3441   void * processB_address = segment.get_address_from_handle(handle);
3442
3443[endsect]
3444
3445[section:allocation_types Object construction function family]
3446
3447When constructing objects in a managed memory segment (managed shared memory,
3448managed mapped files...) associated with a name, the user has a varied object
3449construction family to "construct" or to "construct if not found". [*Boost.Interprocess]
3450can construct a single object or an array of objects. The array can be constructed with
3451the same parameters for all objects or we can define each parameter from a list of iterators:
3452
3453[c++]
3454
3455   //!Allocates and constructs an object of type MyType (throwing version)
3456   MyType *ptr = managed_memory_segment.construct<MyType>("Name") (par1, par2...);
3457
3458   //!Allocates and constructs an array of objects of type MyType (throwing version)
3459   //!Each object receives the same parameters (par1, par2, ...)
3460   MyType *ptr = managed_memory_segment.construct<MyType>("Name")[count](par1, par2...);
3461
3462   //!Tries to find a previously created object. If not present, allocates
3463   //!and constructs an object of type MyType (throwing version)
3464   MyType *ptr = managed_memory_segment.find_or_construct<MyType>("Name") (par1, par2...);
3465
3466   //!Tries to find a previously created object. If not present, allocates and
3467   //!constructs an array of objects of type MyType (throwing version). Each object
3468   //!receives the same parameters (par1, par2, ...)
3469   MyType *ptr = managed_memory_segment.find_or_construct<MyType>("Name")[count](par1, par2...);
3470
3471   //!Allocates and constructs an array of objects of type MyType (throwing version)
3472   //!Each object receives parameters returned with the expression (*it1++, *it2++,... )
3473   MyType *ptr = managed_memory_segment.construct_it<MyType>("Name")[count](it1, it2...);
3474
3475   //!Tries to find a previously created object. If not present, allocates and constructs
3476   //!an array of objects of type MyType (throwing version).  Each object receives
3477   //!parameters returned with the expression (*it1++, *it2++,... )
3478   MyType *ptr = managed_memory_segment.find_or_construct_it<MyType>("Name")[count](it1, it2...);
3479
3480   //!Tries to find a previously created object. Returns a pointer to the object and the
3481   //!count (if it is not an array, returns 1). If not present, the returned pointer is 0
3482   std::pair<MyType *,std::size_t> ret = managed_memory_segment.find<MyType>("Name");
3483
3484   //!Destroys the created object, returns false if not present
3485   bool destroyed = managed_memory_segment.destroy<MyType>("Name");
3486
3487   //!Destroys the created object via pointer
3488   managed_memory_segment.destroy_ptr(ptr);
3489
3490All these functions have a non-throwing version, that
3491is invoked with an additional parameter std::nothrow.
3492For example, for simple object construction:
3493
3494[c++]
3495
3496   //!Allocates and constructs an object of type MyType (no throwing version)
3497   MyType *ptr = managed_memory_segment.construct<MyType>("Name", std::nothrow) (par1, par2...);
3498
3499[endsect]
3500
3501[section:anonymous Anonymous instance construction]
3502
3503Sometimes, the user doesn't want to create class objects associated with a name.
3504For this purpose, [*Boost.Interprocess] can create anonymous objects in a managed
3505memory segment. All named object construction functions are available to construct
3506anonymous objects. To allocate an anonymous objects, the user must use
3507"boost::interprocess::anonymous_instance" name instead of a normal name:
3508
3509[c++]
3510
3511   MyType *ptr = managed_memory_segment.construct<MyType>(anonymous_instance) (par1, par2...);
3512
3513   //Other construct variants can also be used (including non-throwing ones)
3514   ...
3515
3516   //We can only destroy the anonymous object via pointer
3517   managed_memory_segment.destroy_ptr(ptr);
3518
3519Find functions have no sense here, since anonymous objects have no name.
3520We can only destroy the anonymous object via pointer.
3521
3522[endsect]
3523
3524[section:unique Unique instance construction]
3525
3526Sometimes, the user wants to emulate a singleton in a managed memory segment. Obviously,
3527as the managed memory segment is constructed at run-time, the user must construct and
3528destroy this object explicitly. But how can the user be sure that the object is the only
3529object of its type in the managed memory segment? This can be emulated using
3530a named object and checking if it is present before trying to create one, but
3531all processes must agree in the object's name, that can also conflict with
3532other existing names.
3533
3534To solve this, [*Boost.Interprocess] offers a "unique object" creation in a managed memory segment.
3535Only one instance of a class can be created in a managed memory segment using this
3536"unique object" service (you can create more named objects of this class, though)
3537so it makes easier the emulation of singleton-like objects across processes, for example,
3538to design pooled, shared memory allocators. The object can be searched using the type
3539of the class as a key.
3540
3541[c++]
3542
3543   // Construct
3544   MyType *ptr = managed_memory_segment.construct<MyType>(unique_instance) (par1, par2...);
3545
3546   // Find it
3547   std::pair<MyType *,std::size_t> ret = managed_memory_segment.find<MyType>(unique_instance);
3548
3549   // Destroy it
3550   managed_memory_segment.destroy<MyType>(unique_instance);
3551
3552   // Other construct and find variants can also be used (including non-throwing ones)
3553   //...
3554
3555[c++]
3556
3557   // We can also destroy the unique object via pointer
3558   MyType *ptr = managed_memory_segment.construct<MyType>(unique_instance) (par1, par2...);
3559   managed_shared_memory.destroy_ptr(ptr);
3560
3561The find function obtains a pointer to the only object of type T that can be created
3562using this "unique instance" mechanism.
3563
3564[endsect]
3565
3566[section:synchronization Synchronization guarantees]
3567
3568One of the features of named/unique allocations/searches/destructions is that
3569they are [*atomic]. Named allocations use the recursive synchronization scheme defined by the
3570internal `mutex_family` typedef defined of the memory allocation algorithm template
3571parameter (`MemoryAlgorithm`). That is, the mutex type used to synchronize
3572named/unique allocations is defined by the
3573`MemoryAlgorithm::mutex_family::recursive_mutex_type` type. For shared memory,
3574and memory mapped file based managed segments this recursive mutex is defined
3575as [classref boost::interprocess::interprocess_recursive_mutex interprocess_recursive_mutex].
3576
3577If two processes can call:
3578
3579[c++]
3580
3581   MyType *ptr = managed_shared_memory.find_or_construct<MyType>("Name")[count](par1, par2...);
3582
3583at the same time, but only one process will create the object and the other will
3584obtain a pointer to the created object.
3585
3586Raw allocation using `allocate()` can be called also safely while executing
3587named/anonymous/unique allocations, just like when programming a multithreaded
3588application inserting an object in a mutex-protected map does not block other threads
3589from calling new[] while the map thread is searching the place where it has to insert the
3590new object. The synchronization does happen once the map finds the correct place and
3591it has to allocate raw memory to construct the new value.
3592
3593This means that if we are creating or searching for a lot of named objects,
3594we only block creation/searches from other processes but we don't block another
3595process if that process is inserting elements in a shared memory vector.
3596
3597[endsect]
3598
3599[section:index_types Index types for name/object mappings]
3600
3601As seen, managed memory segments, when creating named objects, store the name/object
3602association in an index. The index is a map with the name of the object as a key and
3603a pointer to the object as the mapped type. The default specializations,
3604*managed_shared_memory* and *wmanaged_shared_memory*, use *flat_map_index* as the index type.
3605
3606Each index has its own characteristics, like search-time, insertion time, deletion time,
3607memory use, and memory allocation patterns. [*Boost.Interprocess] offers 3 index types
3608right now:
3609
3610*  [*boost::interprocess::flat_map_index flat_map_index]: Based on boost::interprocess::flat_map, an ordered
3611   vector similar to Loki library's AssocVector class, offers great search time and
3612   minimum memory use. But the vector must be reallocated when is full, so all data
3613   must be copied to the new buffer. Ideal when insertions are mainly in initialization
3614   time and in run-time we just need searches.
3615
3616*  [*boost::interprocess::map_index map_index]: Based on boost::interprocess::map, a managed memory ready
3617   version of std::map. Since it's a node based container, it has no reallocations, the tree
3618   must be just rebalanced sometimes. Offers equilibrated insertion/deletion/search
3619   times with more overhead per node comparing to *boost::interprocess::flat_map_index*.
3620   Ideal when searches/insertions/deletions are in random order.
3621
3622*  [*boost::interprocess::null_index null_index]: This index is for people using a managed
3623   memory segment just for raw memory buffer allocations and they don't make use
3624   of named/unique allocations. This class is just empty and saves some space and
3625   compilation time.
3626   If you try to use named object creation with a managed memory segment using this
3627   index, you will get a compilation error.
3628
3629As an example, if we want to define new managed shared memory class
3630using *boost::interprocess::map* as the index type we
3631just must specify [boost::interprocess::map_index map_index] as a template parameter:
3632
3633[c++]
3634
3635   //This managed memory segment can allocate objects with:
3636   // -> a wchar_t string as key
3637   // -> boost::interprocess::rbtree_best_fit with process-shared mutexes
3638   //       as memory allocation algorithm.
3639   // -> boost::interprocess::map<...> as the index to store name/object mappings
3640   //
3641   typedef boost::interprocess::basic_managed_shared_memory
3642            <  wchar_t
3643            ,  boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family, offset_ptr<void> >
3644            ,  boost::interprocess::map_index
3645            >  my_managed_shared_memory;
3646
3647[*Boost.Interprocess] plans to offer an *unordered_map* based index as soon as this
3648container is included in Boost. If these indexes are not enough for you, you can define
3649your own index type. To know how to do this, go to
3650[link interprocess.customizing_interprocess.custom_indexes Building custom indexes] section.
3651
3652[endsect]
3653
3654[section:managed_memory_segment_segment_manager Segment Manager]
3655
3656All [*Boost.Interprocess] managed memory segment classes construct in their
3657respective memory segments (shared memory, memory mapped files, heap memory...)
3658some structures to implement the memory management algorithm, named allocations,
3659synchronization objects... All these objects are encapsulated in a single object
3660called [*segment manager]. A managed memory mapped file and a managed shared
3661memory use the same [*segment manager] to implement all managed memory segment
3662features, due to the fact that a [*segment manager] is a class that manages
3663a fixed size memory buffer. Since both shared memory or memory mapped files
3664are accessed though a mapped region, and a mapped region is a fixed size
3665memory buffer, a single [*segment manager] class can manage several managed
3666memory segment types.
3667
3668Some [*Boost.Interprocess] classes require a pointer to the segment manager in
3669their constructors, and the segment manager can be obtained from any managed
3670memory segment using `get_segment_manager` member:
3671
3672[c++]
3673
3674   managed_shared_memory::segment_manager *seg_manager =
3675      managed_shm.get_segment_manager();
3676
3677[endsect]
3678
3679[section:managed_memory_segment_information Obtaining information about a constructed object]
3680
3681Once an object is constructed using `construct<>` function family, the
3682programmer can obtain information about the object using a pointer to the
3683object. The programmer can obtain the following information:
3684
3685*  Name of the object: If it's a named instance, the name used in the construction
3686   function is returned, otherwise 0 is returned.
3687
3688*  Length of the object: Returns the number of elements of the object (1 if it's
3689   a single value, >=1 if it's an array).
3690
3691*  The type of construction: Whether the object was constructed using a named,
3692   unique or anonymous construction.
3693
3694Here is an example showing this functionality:
3695
3696[import ../example/doc_managed_construction_info.cpp]
3697[doc_managed_construction_info]
3698
3699[endsect]
3700
3701[section:managed_memory_segment_atomic_func Executing an object function atomically]
3702
3703Sometimes the programmer must execute some code, and needs to execute it with the
3704guarantee that no other process or thread will create or destroy any named, unique
3705or anonymous object while executing the functor. A user might want to create several
3706named objects and initialize them, but those objects should be available for the rest of processes
3707at once.
3708
3709To achieve this, the programmer can use the `atomic_func()` function offered by
3710managed classes:
3711
3712[c++]
3713
3714   //This object function will create several named objects
3715   create_several_objects_func func(/**/);
3716
3717   //While executing the function, no other process will be
3718   //able to create or destroy objects
3719   managed_memory.atomic_func(func);
3720
3721
3722Note that `atomic_func` does not prevent other processes from allocating raw memory
3723or executing member functions for already constructed objects (e.g.: another process
3724might be pushing elements into a vector placed in the segment). The atomic function
3725only blocks named, unique and anonymous creation, search and destruction
3726(concurrent calls to `construct<>`, `find<>`, `find_or_construct<>`, `destroy<>`...)
3727from other processes.
3728
3729[endsect]
3730
3731[endsect]
3732
3733[section:managed_memory_segment_advanced_features Managed Memory Segment Advanced Features]
3734
3735[section:managed_memory_segment_information Obtaining information about the managed segment]
3736
3737These functions are available to obtain information about the managed memory segments:
3738
3739Obtain the size of the memory segment:
3740
3741[c++]
3742
3743   managed_shm.get_size();
3744
3745Obtain the number of free bytes of the segment:
3746
3747[c++]
3748
3749   managed_shm.get_free_memory();
3750
3751Clear to zero the free memory:
3752
3753[c++]
3754
3755   managed_shm.zero_free_memory();
3756
3757Know if all memory has been deallocated, false otherwise:
3758
3759[c++]
3760
3761   managed_shm.all_memory_deallocated();
3762
3763Test internal structures of the managed segment. Returns true
3764if no errors are detected:
3765
3766[c++]
3767
3768   managed_shm.check_sanity();
3769
3770Obtain the number of named and unique objects allocated in the segment:
3771
3772[c++]
3773
3774   managed_shm.get_num_named_objects();
3775   managed_shm.get_num_unique_objects();
3776
3777[endsect]
3778
3779[section:growing_managed_memory Growing managed segments]
3780
3781Once a managed segment is created the managed segment can't be grown. The limitation
3782is not easily solvable: every process attached to the managed segment would need to
3783be stopped, notified of the new size, they would need to remap the managed segment
3784and continue working. Nearly impossible to achieve with a user-level library without
3785the help of the operating system kernel.
3786
3787On the other hand, [*Boost.Interprocess] offers off-line segment growing. What does this
3788mean? That the segment can be grown if no process has mapped the managed segment. If the
3789application can find a moment where no process is attached it can grow or shrink to fit
3790the managed segment.
3791
3792Here we have an example showing how to grow and shrink to fit
3793[classref boost::interprocess::managed_shared_memory managed_shared_memory]:
3794
3795[import ../example/doc_managed_grow.cpp]
3796[doc_managed_grow]
3797
3798[classref boost::interprocess::managed_mapped_file managed_mapped_file] also
3799offers a similar function to grow or shrink_to_fit the managed file.
3800Please, remember that [*no process should be modifying the file/shared memory while
3801the growing/shrinking process is performed]. Otherwise, the managed segment will be
3802corrupted.
3803
3804[endsect]
3805
3806[section:managed_memory_segment_advanced_index_functions Advanced index functions]
3807
3808As mentioned, the managed segment stores the information about named and unique
3809objects in two indexes. Depending on the type of those indexes, the index must
3810reallocate some auxiliary structures when new named or unique allocations are made.
3811For some indexes, if the user knows how many named or unique objects are going to
3812be created it's possible to preallocate some structures to obtain much better
3813performance. (If the index is an ordered vector it can  preallocate memory to avoid
3814reallocations. If the index is a hash structure it can preallocate the bucket array).
3815
3816The following functions reserve memory to make the subsequent allocation of
3817named or unique objects more efficient. These functions are only useful for
3818pseudo-intrusive or non-node indexes (like `flat_map_index`,
3819`iunordered_set_index`). These functions have no effect with the
3820default index (`iset_index`) or other indexes (`map_index`):
3821
3822[c++]
3823
3824   managed_shm.reserve_named_objects(1000);
3825   managed_shm.reserve_unique_objects(1000);
3826
3827[c++]
3828
3829   managed_shm.reserve_named_objects(1000);
3830   managed_shm.reserve_unique_objects(1000);
3831
3832Managed memory segments also offer the possibility to iterate through
3833constructed named and unique objects for debugging purposes. [*Caution: this
3834iteration is not thread-safe] so the user should make sure that no other
3835thread is manipulating named or unique indexes (creating, erasing,
3836reserving...) in the segment. Other operations not involving indexes can
3837be concurrently executed (raw memory allocation/deallocations, for example).
3838
3839The following functions return constant iterators to the range of named and
3840unique objects stored in the managed segment. Depending on the index type,
3841iterators might be invalidated after a named or unique
3842creation/erasure/reserve operation:
3843
3844[c++]
3845
3846   typedef managed_shared_memory::const_named_iterator const_named_it;
3847   const_named_it named_beg = managed_shm.named_begin();
3848   const_named_it named_end = managed_shm.named_end();
3849
3850   typedef managed_shared_memory::const_unique_iterator const_unique_it;
3851   const_unique_it unique_beg = managed_shm.unique_begin();
3852   const_unique_it unique_end = managed_shm.unique_end();
3853
3854   for(; named_beg != named_end; ++named_beg){
3855      //A pointer to the name of the named object
3856      const managed_shared_memory::char_type *name = named_beg->name();
3857      //The length of the name
3858      std::size_t name_len = named_beg->name_length();
3859      //A constant void pointer to the named object
3860      const void *value = named_beg->value();
3861   }
3862
3863   for(; unique_beg != unique_end; ++unique_beg){
3864      //The typeid(T).name() of the unique object
3865      const char *typeid_name = unique_beg->name();
3866      //The length of the name
3867      std::size_t name_len = unique_beg->name_length();
3868      //A constant void pointer to the unique object
3869      const void *value = unique_beg->value();
3870   }
3871
3872[endsect]
3873
3874[section:allocate_aligned Allocating aligned memory portions]
3875
3876Sometimes it's interesting to be able to allocate aligned fragments of memory
3877because of some hardware or software restrictions. Sometimes, having
3878aligned memory is a feature that can be used to improve several
3879memory algorithms.
3880
3881This allocation is similar to the previously shown raw memory allocation but
3882it takes an additional parameter specifying the alignment. There is
3883a restriction for the alignment: [*the alignment must be power of two].
3884
3885If a user wants to allocate many aligned blocks (for example aligned to 128 bytes),
3886the size that minimizes the memory waste is a value that's is nearly a multiple
3887of that alignment (for example 2*128 - some bytes). The reason for this is that
3888every memory allocation usually needs some additional metadata in the first
3889bytes of the allocated buffer. If the user can know the value of "some bytes"
3890and if the first bytes of a free block of memory are used to fulfill the aligned
3891allocation, the rest of the block can be left also aligned and ready for the next
3892aligned allocation. Note that requesting [*a size multiple of the alignment is not optimal]
3893because lefts the next block of memory unaligned due to the needed metadata.
3894
3895Once the programmer knows the size of the payload of every memory allocation,
3896he can request a size that will be optimal to allocate aligned chunks
3897of memory maximizing both the size of the
3898request [*and] the possibilities of future aligned allocations. This information
3899is stored in the PayloadPerAllocation constant of managed memory segments.
3900
3901Here is a small example showing how aligned allocation is used:
3902
3903[import ../example/doc_managed_aligned_allocation.cpp]
3904[doc_managed_aligned_allocation]
3905
3906[endsect]
3907
3908[section:managed_memory_segment_multiple_allocations Multiple allocation functions]
3909
3910[caution This feature is experimental, interface and ABI are unstable]
3911
3912If an application needs to allocate a lot of memory buffers but it needs
3913to deallocate them independently, the application is normally forced to loop
3914calling `allocate()`. Managed memory segments offer an alternative function
3915to pack several allocations in a single call obtaining memory buffers that:
3916
3917*  are packed contiguously in memory (which improves locality)
3918*  can be independently deallocated.
3919
3920This allocation method is much faster
3921than calling `allocate()` in a loop. The downside is that the segment
3922must provide a contiguous memory segment big enough to hold all the allocations.
3923Managed memory segments offer this functionality through `allocate_many()` functions.
3924There are 2 types of `allocate_many` functions:
3925
3926* Allocation of N buffers of memory with the same size.
3927* Allocation of N buffers of memory, each one of different size.
3928
3929[c++]
3930
3931   //!Allocates n_elements of elem_bytes bytes.
3932   //!Throws bad_alloc on failure. chain.size() is not increased on failure.
3933   void allocate_many(size_type elem_bytes, size_type n_elements, multiallocation_chain &chain);
3934
3935   //!Allocates n_elements, each one of element_lengths[i]*sizeof_element bytes.
3936   //!Throws bad_alloc on failure. chain.size() is not increased on failure.
3937   void allocate_many(const size_type *element_lengths, size_type n_elements, size_type sizeof_element, multiallocation_chain &chain);
3938
3939   //!Allocates n_elements of elem_bytes bytes.
3940   //!Non-throwing version. chain.size() is not increased on failure.
3941   void allocate_many(std::nothrow_t, size_type elem_bytes, size_type n_elements, multiallocation_chain &chain);
3942
3943   //!Allocates n_elements, each one of
3944   //!element_lengths[i]*sizeof_element bytes.
3945   //!Non-throwing version. chain.size() is not increased on failure.
3946   void allocate_many(std::nothrow_t, const size_type *elem_sizes, size_type n_elements, size_type sizeof_element, multiallocation_chain &chain);
3947
3948   //!Deallocates all elements contained in chain.
3949   //!Never throws.
3950   void deallocate_many(multiallocation_chain &chain);
3951
3952Here is a small example showing all this functionality:
3953
3954[import ../example/doc_managed_multiple_allocation.cpp]
3955[doc_managed_multiple_allocation]
3956
3957Allocating N buffers of the same size improves the performance of pools
3958and node containers (for example STL-like lists): when inserting a range of
3959forward iterators in a STL-like list, the insertion function can detect the
3960number of needed elements and allocate in a single call. The nodes still
3961can be deallocated.
3962
3963Allocating N buffers of different sizes can be used to speed up allocation in
3964cases where several objects must always be allocated at the same time but
3965deallocated at different times. For example, a class might perform several initial
3966allocations (some header data for a network packet, for example) in its
3967constructor but also allocations of buffers that might be reallocated in the future
3968(the data to be sent through the network). Instead of allocating all the data
3969independently, the constructor might use `allocate_many()` to speed up the
3970initialization, but it still can deallocate and expand the memory of the variable
3971size element.
3972
3973In general, `allocate_many` is useful with large values of N. Overuse
3974of `allocate_many` can increase the effective memory usage,
3975because it can't reuse existing non-contiguous memory fragments that
3976might be available for some of the elements.
3977
3978[endsect]
3979
3980[section:managed_memory_segment_expand_in_place Expand in place memory allocation]
3981
3982When programming some data structures such as vectors, memory reallocation becomes
3983an important tool to improve performance. Managed memory segments offer an advanced
3984reallocation function that offers:
3985
3986*  Forward expansion: An allocated buffer can be expanded so that the end of the buffer
3987   is moved further. New data can be written between the old end and the new end.
3988
3989*  Backwards expansion: An allocated buffer can be expanded so that the beginning of
3990   the buffer is moved backwards. New data can be written between the new beginning
3991   and the old beginning.
3992
3993*  Shrinking: An allocated buffer can be shrunk so that the end of the buffer
3994   is moved backwards. The memory between the new end and the old end can be reused
3995   for future allocations.
3996
3997The expansion can be combined with the allocation of a new buffer if the expansion
3998fails obtaining a function with "expand, if fails allocate a new buffer" semantics.
3999
4000Apart from this features, the function always returns the real size of the
4001allocated buffer, because many times, due to alignment issues the allocated
4002buffer a bit bigger than the requested size. Thus, the programmer can maximize
4003the memory use using `allocation_command`.
4004
4005Here is the declaration of the function:
4006
4007[c++]
4008
4009   enum boost::interprocess::allocation_type
4010   {
4011      //Bitwise OR (|) combinable values
4012      boost::interprocess::allocate_new        = ...,
4013      boost::interprocess::expand_fwd          = ...,
4014      boost::interprocess::expand_bwd          = ...,
4015      boost::interprocess::shrink_in_place     = ...,
4016      boost::interprocess::nothrow_allocation  = ...
4017   };
4018
4019
4020   template<class T>
4021   std::pair<T *, bool>
4022      allocation_command( boost::interprocess::allocation_type command
4023                        , std::size_t limit_size
4024                        , size_type &prefer_in_recvd_out_size
4025                        , T *&reuse_ptr);
4026
4027
4028[*Preconditions for the function]:
4029
4030*  If the parameter command contains the value `boost::interprocess::shrink_in_place` it can't
4031contain any of these values: `boost::interprocess::expand_fwd`, `boost::interprocess::expand_bwd`.
4032
4033*  If the parameter command contains `boost::interprocess::expand_fwd` or `boost::interprocess::expand_bwd`, the parameter
4034   `reuse_ptr` must be non-null and returned by a previous allocation function.
4035
4036*  If the parameter command contains the value `boost::interprocess::shrink_in_place`, the parameter
4037   `limit_size` must be equal or greater than the parameter `preferred_size`.
4038
4039*  If the parameter `command` contains any of these values: `boost::interprocess::expand_fwd` or `boost::interprocess::expand_bwd`,
4040   the parameter `limit_size` must be equal or less than the parameter `preferred_size`.
4041
4042[*Which are the effects of this function:]
4043
4044*  If the parameter command contains the value `boost::interprocess::shrink_in_place`, the function
4045   will try to reduce the size of the memory block referenced by pointer `reuse_ptr`
4046   to the value `preferred_size` moving only the end of the block.
4047   If it's not possible, it will try to reduce the size of the memory block as
4048   much as possible as long as this results in `size(p) <= limit_size`. Success
4049   is reported only if this results in `preferred_size <= size(p)` and `size(p) <= limit_size`.
4050
4051*  If the parameter `command` only contains the value `boost::interprocess::expand_fwd` (with optional
4052   additional `boost::interprocess::nothrow_allocation`), the allocator will try to increase the size of the
4053   memory block referenced by pointer reuse moving only the end of the block to the
4054   value `preferred_size`. If it's not possible, it will try to increase the size
4055   of the memory block as much as possible as long as this results in
4056   `size(p) >= limit_size`. Success is reported only if this results in `limit_size <= size(p)`.
4057
4058*  If the parameter `command` only contains the value `boost::interprocess::expand_bwd` (with optional
4059   additional `boost::interprocess::nothrow_allocation`), the allocator will try to increase the size of
4060   the memory block referenced by pointer `reuse_ptr` only moving the start of the
4061   block to a returned new position `new_ptr`. If it's not possible, it will try to
4062   move the start of the block as much as possible as long as this results in
4063   `size(new_ptr) >= limit_size`. Success is reported only if this results in
4064   `limit_size <= size(new_ptr)`.
4065
4066*  If the parameter `command` only contains the value `boost::interprocess::allocate_new` (with optional
4067   additional `boost::interprocess::nothrow_allocation`), the allocator will try to allocate memory for
4068   `preferred_size` objects. If it's not possible it will try to allocate memory for
4069   at least `limit_size` objects.
4070
4071*  If the parameter `command` only contains a combination of `boost::interprocess::expand_fwd` and
4072   `boost::interprocess::allocate_new`, (with optional additional `boost::interprocess::nothrow_allocation`) the allocator will
4073   try first the forward expansion. If this fails, it would try a new allocation.
4074
4075*  If the parameter `command` only contains a combination of `boost::interprocess::expand_bwd` and
4076   `boost::interprocess::allocate_new` (with optional additional `boost::interprocess::nothrow_allocation`), the allocator will
4077   try first to obtain `preferred_size` objects using both methods if necessary.
4078   If this fails, it will try to obtain `limit_size` objects using both methods if
4079   necessary.
4080
4081*  If the parameter `command` only contains a combination of `boost::interprocess::expand_fwd` and
4082   `boost::interprocess::expand_bwd` (with optional additional `boost::interprocess::nothrow_allocation`), the allocator will
4083   try first forward expansion. If this fails it will try to obtain preferred_size
4084   objects using backwards expansion or a combination of forward and backwards expansion.
4085   If this fails, it will try to obtain `limit_size` objects using both methods if
4086   necessary.
4087
4088*  If the parameter `command` only contains a combination of allocation_new,
4089   `boost::interprocess::expand_fwd` and `boost::interprocess::expand_bwd`, (with optional additional `boost::interprocess::nothrow_allocation`)
4090   the allocator will try first forward expansion. If this fails it will try to obtain
4091   preferred_size objects using new allocation, backwards expansion or a combination of
4092   forward and backwards expansion. If this fails, it will try to obtain `limit_size`
4093   objects using the same methods.
4094
4095*  The allocator always writes the size or the expanded/allocated/shrunk memory block
4096   in `received_size`. On failure the allocator writes in `received_size` a possibly
4097   successful `limit_size` parameter for a new call.
4098
4099[*Throws an exception if two conditions are met:]
4100
4101*  The allocator is unable to allocate/expand/shrink the memory or there is an
4102   error in preconditions
4103
4104*  The parameter command does not contain `boost::interprocess::nothrow_allocation`.
4105
4106[*This function returns:]
4107
4108*  The address of the allocated memory or the new address of the expanded memory
4109   as the first member of the pair. If the parameter command contains
4110   `boost::interprocess::nothrow_allocation` the first member will be 0
4111   if the allocation/expansion fails or there is an error in preconditions.
4112
4113*  The second member of the pair will be false if the memory has been allocated,
4114   true if the memory has been expanded. If the first member is 0, the second member
4115   has an undefined value.
4116
4117[*Notes:]
4118
4119*  If the user chooses `char` as template argument the returned buffer will
4120   be suitably aligned to hold any type.
4121*  If the user chooses `char` as template argument and a backwards expansion is
4122   performed, although properly aligned, the returned buffer might not be
4123   suitable because the distance between the new beginning and the old beginning
4124   might not multiple of the type the user wants to construct, since due to internal
4125   restrictions the expansion can be slightly bigger than the requested bytes. [*When
4126   performing backwards expansion, if you have already constructed objects in the
4127   old buffer, make sure to specify correctly the type.]
4128
4129Here is a small example that shows the use of `allocation_command`:
4130
4131[import ../example/doc_managed_allocation_command.cpp]
4132[doc_managed_allocation_command]
4133
4134`allocation_command` is a very powerful function that can lead to important
4135performance gains. It's specially useful when programming vector-like data
4136structures where the programmer can minimize both the number of allocation
4137requests and the memory waste.
4138
4139[endsect]
4140
4141[section:copy_on_write_read_only Opening managed shared memory and mapped files with Copy On Write or Read Only modes]
4142
4143When mapping a memory segment based on shared memory or files, there is an option to
4144open them using [*open_copy_on_write] option. This option is similar to `open_only` but
4145every change the programmer does with this managed segment is kept private to this process
4146and is not translated to the underlying device (shared memory or file).
4147
4148The underlying shared memory or file is opened as read-only so several processes can
4149share an initial managed segment and make private changes to it. If many processes
4150open a managed segment in copy on write mode and not modified pages from the managed
4151segment will be shared between all those processes, with considerable memory savings.
4152
4153Opening managed shared memory and mapped files with [*open_read_only] maps the
4154underlying device in memory with [*read-only] attributes. This means that any attempt
4155to write that memory, either creating objects or locking any mutex might result in an
4156page-fault error (and thus, program termination) from the OS. Read-only mode opens
4157the underlying device (shared memory, file...) in read-only mode and
4158can result in considerable memory savings if several processes just want to process
4159a managed memory segment without modifying it. Read-only mode operations are limited:
4160
4161*  Read-only mode must be used only from managed classes. If the programmer obtains
4162   the segment manager and tries to use it directly it might result in an access violation.
4163   The reason for this is that the segment manager is placed in the underlying device
4164   and does not nothing about the mode it's been mapped in memory.
4165
4166*  Only const member functions from managed segments should be used.
4167
4168*  Additionally, the `find<>` member function avoids using internal locks and can be
4169   used to look for named and unique objects.
4170
4171Here is an example that shows the use of these two open modes:
4172
4173[import ../example/doc_managed_copy_on_write.cpp]
4174[doc_managed_copy_on_write]
4175
4176[endsect]
4177
4178[endsect]
4179
4180[section:managed_heap_memory_external_buffer Managed Heap Memory And Managed External Buffer]
4181
4182[*Boost.Interprocess] offers managed shared memory between processes using
4183`managed_shared_memory` or `managed_mapped_file`. Two processes just map the same
4184the memory mappable resource and read from and write to that object.
4185
4186Many times, we don't want to use that shared memory approach and we prefer
4187to send serialized data through network, local socket or message queues. Serialization
4188can be done through [*Boost.Serialization] or similar library. However, if two processes
4189share the same ABI (application binary interface), we could use the same object and
4190container construction capabilities of `managed_shared_memory` or `managed_heap_memory`
4191to build all the information in a single buffer that will be sent, for example,
4192though message queues. The receiver would just copy the data to a local buffer, and it
4193could read or modify it directly without deserializing the data . This approach can be
4194much more efficient that a complex serialization mechanism.
4195
4196Applications for [*Boost.Interprocess] services using non-shared memory buffers:
4197
4198* Create and use STL compatible containers and allocators,
4199  in systems where dynamic memory is not recommendable.
4200
4201* Build complex, easily serializable databases in a single buffer:
4202
4203   * To share data between threads
4204
4205   * To save and load information from/to files.
4206
4207*  Duplicate information (containers, allocators, etc...) just copying the contents of
4208   one buffer to another one.
4209
4210*  Send complex information and objects/databases using serial/inter-process/network
4211   communications.
4212
4213To help with this management, [*Boost.Interprocess] provides two useful classes,
4214`basic_managed_heap_memory` and `basic_managed_external_buffer`:
4215
4216[section:managed_external_buffer Managed External Buffer: Constructing all Boost.Interprocess objects in a user provided buffer]
4217
4218Sometimes, the user wants to create simple objects, STL compatible containers, STL compatible
4219strings and more, all in a single buffer. This buffer could be a big static buffer,
4220a memory-mapped auxiliary device or any other user buffer.
4221
4222This would allow an easy serialization and we-ll just need to copy the buffer to duplicate
4223all the objects created in the original buffer, including complex objects like
4224maps, lists.... [*Boost.Interprocess] offers managed memory segment classes to handle user
4225provided buffers that allow the same functionality as shared memory classes:
4226
4227[c++]
4228
4229   //Named object creation managed memory segment
4230   //All objects are constructed in a user provided buffer
4231   template <
4232               class CharType,
4233               class MemoryAlgorithm,
4234               template<class IndexConfig> class IndexType
4235            >
4236   class basic_managed_external_buffer;
4237
4238   //Named object creation managed memory segment
4239   //All objects are constructed in a user provided buffer
4240   //   Names are c-strings,
4241   //   Default memory management algorithm
4242   //    (rbtree_best_fit with no mutexes and relative pointers)
4243   //   Name-object mappings are stored in the default index type (flat_map)
4244   typedef basic_managed_external_buffer <
4245      char,
4246      rbtree_best_fit<null_mutex_family, offset_ptr<void> >,
4247      flat_map_index
4248      >  managed_external_buffer;
4249
4250   //Named object creation managed memory segment
4251   //All objects are constructed in a user provided buffer
4252   //   Names are wide-strings,
4253   //   Default memory management algorithm
4254   //    (rbtree_best_fit with no mutexes and relative pointers)
4255   //   Name-object mappings are stored in the default index type (flat_map)
4256   typedef basic_managed_external_buffer<
4257      wchar_t,
4258      rbtree_best_fit<null_mutex_family, offset_ptr<void> >,
4259      flat_map_index
4260      >  wmanaged_external_buffer;
4261
4262To use a managed external buffer, you must include the following header:
4263
4264[c++]
4265
4266   #include <boost/interprocess/managed_external_buffer.hpp>
4267
4268Let's see an example of the use of managed_external_buffer:
4269
4270[import ../example/doc_managed_external_buffer.cpp]
4271[doc_managed_external_buffer]
4272
4273[*Boost.Interprocess] STL compatible allocators can also be used to place STL
4274compatible containers in the user segment.
4275
4276[classref boost::interprocess::basic_managed_external_buffer basic_managed_external_buffer] can
4277be also useful to build small databases for embedded systems limiting the size of
4278the used memory to a predefined memory chunk, instead of letting the database
4279fragment the heap memory.
4280
4281[endsect]
4282
4283[section:managed_heap_memory Managed Heap Memory: Boost.Interprocess machinery in heap memory]
4284
4285The use of heap memory (new/delete) to obtain a buffer where the user wants to store all
4286his data is very common, so [*Boost.Interprocess] provides some specialized
4287classes that work exclusively with heap memory.
4288
4289These are the classes:
4290
4291[c++]
4292
4293   //Named object creation managed memory segment
4294   //All objects are constructed in a single buffer allocated via new[]
4295   template <
4296               class CharType,
4297               class MemoryAlgorithm,
4298               template<class IndexConfig> class IndexType
4299            >
4300   class basic_managed_heap_memory;
4301
4302   //Named object creation managed memory segment
4303   //All objects are constructed in a single buffer allocated via new[]
4304   //   Names are c-strings,
4305   //   Default memory management algorithm
4306   //    (rbtree_best_fit with no mutexes and relative pointers)
4307   //   Name-object mappings are stored in the default index type (flat_map)
4308   typedef basic_managed_heap_memory <
4309      char,
4310      rbtree_best_fit<null_mutex_family>,
4311      flat_map_index
4312      >  managed_heap_memory;
4313
4314   //Named object creation managed memory segment
4315   //All objects are constructed in a single buffer allocated via new[]
4316   //   Names are wide-strings,
4317   //   Default memory management algorithm
4318   //    (rbtree_best_fit with no mutexes and relative pointers)
4319   //   Name-object mappings are stored in the default index type (flat_map)
4320   typedef basic_managed_heap_memory<
4321      wchar_t,
4322      rbtree_best_fit<null_mutex_family>,
4323      flat_map_index
4324      >  wmanaged_heap_memory;
4325
4326To use a managed heap memory, you must include the following header:
4327
4328[c++]
4329
4330   #include <boost/interprocess/managed_heap_memory.hpp>
4331
4332The use is exactly the same as
4333[classref boost::interprocess::basic_managed_external_buffer basic_managed_external_buffer],
4334except that memory is created by
4335the managed memory segment itself using dynamic (new/delete) memory.
4336
4337[*basic_managed_heap_memory] also offers a `grow(std::size_t extra_bytes)` function that
4338tries to resize internal heap memory so that we have room for more objects.
4339But *be careful*, if memory is reallocated, the old buffer will be copied into
4340the new one so all the objects will be binary-copied to the new buffer.
4341To be able to use this function, all pointers constructed in the heap buffer that
4342point to objects in the heap buffer must be relative pointers (for example `offset_ptr`).
4343Otherwise, the result is undefined. Here is an example:
4344
4345[import ../example/doc_managed_heap_memory.cpp]
4346[doc_managed_heap_memory]
4347
4348[endsect]
4349
4350[section:managed_heap_memory_external_buffer_diff Differences between managed memory segments]
4351
4352All managed memory segments have similar capabilities
4353(memory allocation inside the memory segment, named object construction...),
4354but there are some remarkable differences between [*managed_shared_memory],
4355[*managed_mapped_file] and [*managed_heap_memory], [*managed_external_file].
4356
4357*  Default specializations of managed shared memory and mapped file use process-shared
4358   mutexes. Heap memory and external buffer have no internal synchronization by default.
4359   The cause is that the first two are thought to be shared between processes (although
4360   memory mapped files could be used just to obtain a persistent object data-base for a
4361   process) whereas the last two are thought to be used inside one process to construct
4362   a serialized named object data-base that can be sent though serial interprocess
4363   communications (like message queues, localhost network...).
4364
4365*  The first two create a system-global object (a shared memory object or a file) shared
4366   by several processes, whereas the last two are objects that don't create system-wide
4367   resources.
4368
4369[endsect]
4370
4371[section:shared_message_queue_ex Example: Serializing a database through the message queue]
4372
4373To see the utility of managed heap memory and managed external buffer classes,
4374the following example shows how a message queue can be used to serialize a whole
4375database constructed in a memory buffer using [*Boost.Interprocess], send the database
4376through a message queue and duplicated in another buffer:
4377
4378[import ../test/message_queue_test.cpp]
4379[message_queue_test_test_serialize_db]
4380
4381[endsect]
4382
4383[endsect]
4384
4385[endsect]
4386
4387[section:allocators_containers Allocators, containers and memory allocation algorithms]
4388
4389[section:allocator_introduction Introduction to Interprocess allocators]
4390
4391As seen, [*Boost.Interprocess] offers raw memory allocation and object construction
4392using managed memory segments (managed shared memory, managed mapped files...) and
4393one of the first user requests is the use of containers in managed shared memories.
4394To achieve this, [*Boost.Interprocess] makes use of managed memory segment's
4395memory allocation algorithms to build several memory allocation schemes, including
4396general purpose and node allocators.
4397
4398[*Boost.Interprocess] STL compatible allocators are configurable via template parameters.
4399Allocators define their `pointer` typedef based on the `void_pointer` typedef of the segment manager
4400passed as template argument. When this `segment_manager::void_pointer` is a relative pointer,
4401(for example, `offset_ptr<void>`) the user can place these allocators in
4402memory mapped in different base addresses in several processes.
4403
4404[section:allocator_properties Properties of [*Boost.Interprocess] allocators]
4405
4406Container allocators are normally default-constructible because the are stateless.
4407`std::allocator` and [*Boost.Pool's] `boost::pool_allocator`/`boost::fast_pool_allocator`
4408are examples of default-constructible allocators.
4409
4410On the other hand, [*Boost.Interprocess] allocators need to allocate memory from a
4411concrete memory segment and not from a system-wide memory source (like the heap).
4412[*Boost.Interprocess] allocators are [*stateful], which means that they must be
4413configured to tell them where the shared memory or the memory mapped file is.
4414
4415This information is transmitted at compile-time and run-time: The allocators
4416receive a template parameter defining the type of the segment manager and
4417their constructor receive a pointer to the segment manager of the managed memory
4418segment where the user wants to allocate the values.
4419
4420[*Boost.Interprocess] allocators have [*no default-constructors] and containers
4421must be explicitly initialized with a configured allocator:
4422
4423[c++]
4424
4425   //The allocators must be templatized with the segment manager type
4426   typedef any_interprocess_allocator
4427      <int, managed_shared_memory::segment_manager, ...> Allocator;
4428
4429   //The allocator must be constructed with a pointer to the segment manager
4430   Allocator alloc_instance (segment.get_segment_manager(), ...);
4431
4432   //Containers must be initialized with a configured allocator
4433   typedef my_list<int, Allocator> MyIntList;
4434   MyIntList mylist(alloc_inst);
4435
4436   //This would lead to a compilation error, because
4437   //the allocator has no default constructor
4438   //MyIntList mylist;
4439
4440[*Boost.Interprocess] allocators also have a `get_segment_manager()` function
4441that returns the underlying segment manager that they have received in the
4442constructor:
4443
4444[c++]
4445
4446   Allocator::segment_manager s = alloc_instance.get_segment_manager();
4447   AnotherType *a = s->construct<AnotherType>(anonymous_instance)(/*Parameters*/);
4448
4449[endsect]
4450
4451[section:allocator_swapping Swapping Boost.Interprocess allocators]
4452
4453When swapping STL containers, there is an active discussion on what to do with
4454the allocators. Some STL implementations, for example Dinkumware from Visual .NET 2003,
4455perform a deep swap of the whole container through a temporary when allocators are not equal.
4456The [@http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2004/n1599.html proposed resolution]
4457to container swapping is that allocators should be swapped in a non-throwing way.
4458
4459Unfortunately, this approach is not valid with shared memory. Using heap allocators, if
4460Group1 of node allocators share a common segregated storage, and Group2 share another common
4461segregated storage, a simple pointer swapping is needed to swap an allocator of Group1 and another
4462allocator of Group2. But when the user wants to swap two shared memory allocators, each one
4463placed in a different shared memory segment, this is not possible. As generally shared memory
4464is mapped in different addresses in each process, a pointer placed in one segment can't point
4465to any object placed in other shared memory segment, since in each process, the distance between
4466the segments is different. However, if both shared memory allocators are in the same segment,
4467a non-throwing swap is possible, just like heap allocators.
4468
4469Until a final resolution is achieved. [*Boost.Interprocess] allocators implement a non-throwing
4470swap function that swaps internal pointers. If an allocator placed in a shared memory segment is
4471swapped with other placed in a different shared memory segment, the result is undefined. But a
4472crash is quite sure.
4473
4474[endsect]
4475
4476[section:allocator allocator: A general purpose allocator for managed memory segments]
4477
4478The [classref boost::interprocess::allocator allocator] class defines an allocator class that
4479uses the managed memory segment's algorithm to allocate and deallocate memory. This is
4480achieved through the [*segment manager] of the managed memory segment. This allocator
4481is the equivalent for managed memory segments of the standard `std::allocator`.
4482[classref boost::interprocess::allocator allocator]
4483is templatized with the allocated type, and the segment manager.
4484
4485[*Equality:] Two [classref boost::interprocess::allocator allocator] instances
4486constructed with the same segment manager compare equal. If an instance is
4487created using copy constructor, that instance compares equal with the original one.
4488
4489[*Allocation thread-safety:] Allocation and deallocation are implemented as calls
4490to the segment manager's allocation function so the allocator offers the same
4491thread-safety as the segment manager.
4492
4493To use [classref boost::interprocess::allocator allocator] you must include
4494the following header:
4495
4496[c++]
4497
4498   #include <boost/interprocess/allocators/allocator.hpp>
4499
4500
4501[classref boost::interprocess::allocator allocator] has the following declaration:
4502
4503[c++]
4504
4505   namespace boost {
4506   namespace interprocess {
4507
4508   template<class T, class SegmentManager>
4509   class allocator;
4510
4511   }  //namespace interprocess {
4512   }  //namespace boost {
4513
4514The allocator just provides the needed typedefs and forwards all allocation
4515and deallocation requests to the segment manager passed in the constructor, just
4516like `std::allocator` forwards the requests to `operator new[]`.
4517
4518Using [classref boost::interprocess::allocator allocator] is straightforward:
4519
4520[import ../example/doc_allocator.cpp]
4521[doc_allocator]
4522
4523[endsect]
4524
4525[endsect]
4526
4527[section:stl_allocators_segregated_storage Segregated storage node allocators]
4528
4529Variable size memory algorithms waste
4530some space in management information for each allocation. Sometimes,
4531usually for small objects, this is not acceptable. Memory algorithms can
4532also fragment the managed memory segment under some allocation and
4533deallocation schemes, reducing their performance. When allocating
4534many objects of the same type, a simple segregated storage becomes
4535a fast and space-friendly allocator, as explained in the
4536[@http://www.boost.org/libs/pool/ [*Boost.Pool]] library.
4537
4538Segregate storage node
4539allocators allocate large memory chunks from a general purpose memory
4540allocator and divide that chunk into several nodes. No bookkeeping information
4541is stored in the nodes to achieve minimal memory waste: free nodes are linked
4542using a pointer constructed in the memory of the node.
4543
4544[*Boost.Interprocess]
4545offers 3 allocators based on this segregated storage algorithm:
4546[classref boost::interprocess::node_allocator node_allocator],
4547[classref boost::interprocess::private_node_allocator private_node_allocator] and
4548[classref boost::interprocess::cached_node_allocator cached_node_allocator].
4549
4550To know the details of the implementation of
4551of the segregated storage pools see the
4552[link interprocess.architecture.allocators_containers.implementation_segregated_storage_pools Implementation of [*Boost.Interprocess] segregated storage pools]
4553section.
4554
4555[section:segregated_allocators_common Additional parameters and functions of segregated storage node allocators]
4556
4557[classref boost::interprocess::node_allocator node_allocator],
4558[classref boost::interprocess::private_node_allocator private_node_allocator] and
4559[classref boost::interprocess::cached_node_allocator cached_node_allocator] implement
4560the standard allocator interface and the functions explained in the
4561[link interprocess.allocators_containers.allocator_introduction.allocator_properties Properties of Boost.Interprocess allocators].
4562
4563All these allocators are templatized by 3 parameters:
4564
4565*  `class T`: The type to be allocated.
4566*  `class SegmentManager`: The type of the segment manager that will be passed in the constructor.
4567*  `std::size_t NodesPerChunk`: The number of nodes that a memory chunk will contain.
4568   This value will define the size of the memory the pool will request to the
4569   segment manager when the pool runs out of nodes. This parameter has a default value.
4570
4571These allocators also offer the `deallocate_free_chunks()` function. This function will
4572traverse all the memory chunks of the pool and will return to the managed memory segment
4573the free chunks of memory. If this function is not used, deallocating the free chunks does
4574not happen until the pool is destroyed so the only way to return memory allocated
4575by the pool to the segment before destructing the pool is calling manually this function.
4576This function is quite time-consuming because it has quadratic complexity (O(N^2)).
4577
4578[endsect]
4579
4580[section:node_allocator node_allocator: A process-shared segregated storage]
4581
4582For heap-memory node allocators (like [*Boost.Pool's] `boost::fast_pool_allocator`
4583usually a global, thread-shared singleton
4584pool is used for each node size. This is not possible if you try to share
4585a node allocator between processes. To achieve this sharing
4586[classref boost::interprocess::node_allocator node_allocator]
4587uses the segment manager's unique type allocation service
4588(see [link interprocess.managed_memory_segments.managed_memory_segment_features.unique Unique instance construction] section).
4589
4590In the initialization, a
4591[classref boost::interprocess::node_allocator node_allocator]
4592object searches this unique object in
4593the segment. If it is not preset, it builds one.  This way, all
4594[classref boost::interprocess::node_allocator node_allocator]
4595objects built inside a memory segment share a unique memory pool.
4596
4597The common segregated storage is not only shared between node_allocators of the
4598same type, but it is also shared between all node allocators that allocate objects
4599of the same size, for example, [*node_allocator<uint32>] and [*node_allocator<float32>].
4600This saves a lot of memory but also imposes an synchronization overhead for each
4601node allocation.
4602
4603The dynamically created common segregated storage
4604integrates a reference count so that a
4605[classref boost::interprocess::node_allocator node_allocator]
4606can know if any other
4607[classref boost::interprocess::node_allocator node_allocator]
4608is attached to the same common segregated storage. When the last
4609allocator attached to the pool is destroyed, the pool is destroyed.
4610
4611[*Equality:] Two [classref boost::interprocess::node_allocator node_allocator] instances
4612constructed with the same segment manager compare equal. If an instance is
4613created using copy constructor, that instance compares equal with the original one.
4614
4615[*Allocation thread-safety:] Allocation and deallocation are implemented as calls
4616to the shared pool. The shared pool offers the same synchronization guarantees
4617as the segment manager.
4618
4619To use [classref boost::interprocess::node_allocator node_allocator],
4620you must include the following header:
4621
4622[c++]
4623
4624   #include <boost/interprocess/allocators/node_allocator.hpp>
4625
4626[classref boost::interprocess::node_allocator node_allocator] has the following declaration:
4627
4628[c++]
4629
4630   namespace boost {
4631   namespace interprocess {
4632
4633   template<class T, class SegmentManager, std::size_t NodesPerChunk = ...>
4634   class node_allocator;
4635
4636   }  //namespace interprocess {
4637   }  //namespace boost {
4638
4639An example using [classref boost::interprocess::node_allocator node_allocator]:
4640
4641[import ../example/doc_node_allocator.cpp]
4642[doc_node_allocator]
4643
4644[endsect]
4645
4646[section:private_node_allocator private_node_allocator: a private segregated storage]
4647
4648As said, the node_allocator shares a common segregated storage between
4649node_allocators that allocate objects of the same size and this optimizes
4650memory usage. However, it needs a unique/named object construction feature
4651so that this sharing can be possible. Also
4652imposes a synchronization overhead per node allocation because of this share.
4653Sometimes, the unique object service is not available (for example, when
4654building index types to implement the named allocation service itself) or the
4655synchronization overhead is not acceptable. Many times the programmer wants to
4656make sure that the pool is destroyed when the allocator is destroyed, to free
4657the memory as soon as possible.
4658
4659So [*private_node_allocator] uses the same segregated storage as `node_allocator`,
4660but each [*private_node_allocator] has its own segregated storage pool. No synchronization
4661is used when allocating nodes, so there is far less overhead for an operation
4662that usually involves just a few pointer operations when allocating and
4663deallocating a node.
4664
4665[*Equality:] Two [classref boost::interprocess::private_node_allocator private_node_allocator]
4666instances [*never] compare equal. Memory allocated with one allocator [*can't] be
4667deallocated with another one.
4668
4669[*Allocation thread-safety:] Allocation and deallocation are [*not] thread-safe.
4670
4671To use [classref boost::interprocess::private_node_allocator private_node_allocator],
4672you must include the following header:
4673
4674[c++]
4675
4676   #include <boost/interprocess/allocators/private_node_allocator.hpp>
4677
4678[classref boost::interprocess::private_node_allocator private_node_allocator]
4679has the following declaration:
4680
4681[c++]
4682
4683   namespace boost {
4684   namespace interprocess {
4685
4686   template<class T, class SegmentManager, std::size_t NodesPerChunk = ...>
4687   class private_node_allocator;
4688
4689   }  //namespace interprocess {
4690   }  //namespace boost {
4691
4692An example using [classref boost::interprocess::private_node_allocator private_node_allocator]:
4693
4694[import ../example/doc_private_node_allocator.cpp]
4695[doc_private_node_allocator]
4696
4697[endsect]
4698
4699[section:cached_node_allocator cached_node_allocator: caching nodes to avoid overhead]
4700
4701The total node sharing of [classref boost::interprocess::node_allocator node_allocator] can impose a high overhead for some
4702applications and the minimal synchronization overhead of [classref boost::interprocess::private_node_allocator private_node_allocator]
4703can impose a unacceptable memory waste for other applications.
4704
4705To solve this, [*Boost.Interprocess] offers an allocator,
4706[classref boost::interprocess::cached_node_allocator cached_node_allocator], that
4707allocates nodes from the common pool but caches some of them privately so that following
4708allocations have no synchronization overhead. When the cache is full, the allocator
4709returns some cached nodes to the common pool, and those will be available to other
4710allocators.
4711
4712[*Equality:] Two [classref boost::interprocess::cached_node_allocator cached_node_allocator]
4713instances constructed with the same segment manager compare equal. If an instance is
4714created using copy constructor, that instance compares equal with the original one.
4715
4716[*Allocation thread-safety:] Allocation and deallocation are [*not] thread-safe.
4717
4718To use [classref boost::interprocess::cached_node_allocator cached_node_allocator],
4719you must include the following header:
4720
4721[c++]
4722
4723   #include <boost/interprocess/allocators/cached_node_allocator.hpp>
4724
4725[classref boost::interprocess::cached_node_allocator cached_node_allocator]
4726has the following declaration:
4727
4728[c++]
4729
4730   namespace boost {
4731   namespace interprocess {
4732
4733   template<class T, class SegmentManager, std::size_t NodesPerChunk = ...>
4734   class cached_node_allocator;
4735
4736   }  //namespace interprocess {
4737   }  //namespace boost {
4738
4739A [classref boost::interprocess::cached_node_allocator cached_node_allocator] instance
4740and a [classref boost::interprocess::node_allocator node_allocator] instance
4741share the same pool if both instances receive the same template parameters. This means
4742that nodes returned to the shared pool by one of them can be reused by the other.
4743Please note that this does not mean that both allocators compare equal, this is just
4744information for programmers that want to maximize the use of the pool.
4745
4746[classref boost::interprocess::cached_node_allocator cached_node_allocator], offers
4747additional functions to control the cache (the cache can be controlled per instance):
4748
4749*  `void set_max_cached_nodes(std::size_t n)`: Sets the maximum cached nodes limit.
4750   If cached nodes reach the limit, some are returned to the shared pool.
4751
4752*  `std::size_t get_max_cached_nodes() const`: Returns the maximum cached nodes limit.
4753
4754*  `void deallocate_cache()`: Returns the cached nodes to the shared pool.
4755
4756An example using [classref boost::interprocess::cached_node_allocator cached_node_allocator]:
4757
4758[import ../example/doc_cached_node_allocator.cpp]
4759[doc_cached_node_allocator]
4760
4761[endsect]
4762
4763[endsect]
4764
4765[section:stl_allocators_adaptive Adaptive pool node allocators]
4766
4767Node allocators based on simple segregated storage algorithm are both
4768space-efficient and fast but they have a problem: they only can grow. Every allocated
4769node avoids any payload to store additional data and that leads to the following limitation:
4770when a node is deallocated, it's stored in a free list of nodes but memory is not
4771returned to the segment manager so a deallocated
4772node can be only reused by other containers using the same node pool.
4773
4774This behaviour can be problematic if several containers use
4775[classref boost::interprocess::node_allocator] to temporarily allocate a lot
4776of objects but they end storing a few of them: the node pool will be full of nodes
4777that won't be reused wasting memory from the segment.
4778
4779Adaptive pool based allocators trade some space (the overhead can be as low as 1%)
4780and performance (acceptable for many applications) with the ability to return free chunks
4781of nodes to the memory segment, so that they can be used by any other container or managed
4782object construction. To know the details of the implementation of
4783of "adaptive pools" see the
4784[link interprocess.architecture.allocators_containers.implementation_adaptive_pools Implementation of [*Boost.Intrusive] adaptive pools]
4785section.
4786
4787Like with segregated storage based node allocators, Boost.Interprocess offers
47883 new allocators: [classref boost::interprocess::adaptive_pool adaptive_pool],
4789[classref boost::interprocess::private_adaptive_pool private_adaptive_pool],
4790[classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool].
4791
4792[section:adaptive_allocators_common Additional parameters and functions of adaptive pool node allocators]
4793
4794[classref boost::interprocess::adaptive_pool adaptive_pool],
4795[classref boost::interprocess::private_adaptive_pool private_adaptive_pool] and
4796[classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool] implement
4797the standard allocator interface and the functions explained in the
4798[link interprocess.allocators_containers.allocator_introduction.allocator_properties Properties of Boost.Interprocess allocators].
4799
4800All these allocators are templatized by 4 parameters:
4801
4802*  `class T`: The type to be allocated.
4803*  `class SegmentManager`: The type of the segment manager that will be passed in the constructor.
4804*  `std::size_t NodesPerChunk`: The number of nodes that a memory chunk will contain.
4805   This value will define the size of the memory the pool will request to the
4806   segment manager when the pool runs out of nodes. This parameter has a default value.
4807*  `std::size_t MaxFreeChunks`: The maximum number of free chunks that the pool
4808   will hold. If this limit is reached the pool returns the chunks to the segment manager.
4809   This parameter has a default value.
4810
4811These allocators also offer the `deallocate_free_chunks()` function. This function will
4812traverse all the memory chunks of the pool and will return to the managed memory segment
4813the free chunks of memory. This function is much faster than for segregated storage
4814allocators, because the adaptive pool algorithm offers constant-time access to free
4815chunks.
4816
4817[endsect]
4818
4819[section:adaptive_pool adaptive_pool: a process-shared adaptive pool]
4820
4821Just like [classref boost::interprocess::node_allocator node_allocator]
4822a global, process-thread pool is used for each node size. In the
4823initialization, [classref boost::interprocess::adaptive_pool adaptive_pool]
4824searches the pool in the segment. If it is not preset, it builds one.
4825The adaptive pool, is created using a unique name.
4826The adaptive pool it is also shared between
4827all node_allocators that allocate objects  of the same size, for example,
4828[*adaptive_pool<uint32>] and [*adaptive_pool<float32>].
4829
4830The common adaptive pool is destroyed when all the allocators attached
4831to the pool are destroyed.
4832
4833[*Equality:] Two [classref boost::interprocess::adaptive_pool adaptive_pool] instances
4834constructed with the same segment manager compare equal. If an instance is
4835created using copy constructor, that instance compares equal with the original one.
4836
4837[*Allocation thread-safety:] Allocation and deallocation are implemented as calls
4838to the shared pool. The shared pool offers the same synchronization guarantees
4839as the segment manager.
4840
4841To use [classref boost::interprocess::adaptive_pool adaptive_pool],
4842you must include the following header:
4843
4844[c++]
4845
4846   #include <boost/interprocess/allocators/adaptive_pool.hpp>
4847
4848[classref boost::interprocess::adaptive_pool adaptive_pool] has the following declaration:
4849
4850[c++]
4851
4852   namespace boost {
4853   namespace interprocess {
4854
4855   template<class T, class SegmentManager, std::size_t NodesPerChunk = ..., std::size_t MaxFreeChunks = ...>
4856   class adaptive_pool;
4857
4858   }  //namespace interprocess {
4859   }  //namespace boost {
4860
4861An example using [classref boost::interprocess::adaptive_pool adaptive_pool]:
4862
4863[import ../example/doc_adaptive_pool.cpp]
4864[doc_adaptive_pool]
4865
4866[endsect]
4867
4868[section:private_adaptive_pool private_adaptive_pool: a private adaptive pool]
4869
4870Just like [classref boost::interprocess::private_node_allocator private_node_allocator]
4871owns a private segregated storage pool,
4872[classref boost::interprocess::private_adaptive_pool private_adaptive_pool] owns
4873its own adaptive pool. If the user wants to avoid the excessive node allocation
4874synchronization overhead in a container
4875[classref boost::interprocess::private_adaptive_pool private_adaptive_pool]
4876is a good choice.
4877
4878[*Equality:] Two [classref boost::interprocess::private_adaptive_pool private_adaptive_pool]
4879instances [*never] compare equal. Memory allocated with one allocator [*can't] be
4880deallocated with another one.
4881
4882[*Allocation thread-safety:] Allocation and deallocation are [*not] thread-safe.
4883
4884To use [classref boost::interprocess::private_adaptive_pool private_adaptive_pool],
4885you must include the following header:
4886
4887[c++]
4888
4889   #include <boost/interprocess/allocators/private_adaptive_pool.hpp>
4890
4891[classref boost::interprocess::private_adaptive_pool private_adaptive_pool]
4892has the following declaration:
4893
4894[c++]
4895
4896   namespace boost {
4897   namespace interprocess {
4898
4899   template<class T, class SegmentManager, std::size_t NodesPerChunk = ..., std::size_t MaxFreeChunks = ...>
4900   class private_adaptive_pool;
4901
4902   }  //namespace interprocess {
4903   }  //namespace boost {
4904
4905An example using [classref boost::interprocess::private_adaptive_pool private_adaptive_pool]:
4906
4907[import ../example/doc_private_adaptive_pool.cpp]
4908[doc_private_adaptive_pool]
4909
4910[endsect]
4911
4912[section:cached_adaptive_pool cached_adaptive_pool: Avoiding synchronization overhead]
4913
4914Adaptive pools have also a cached version. In this allocator the allocator caches
4915some nodes to avoid the synchronization and bookkeeping overhead of the shared
4916adaptive pool.
4917[classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool]
4918allocates nodes from the common adaptive pool but caches some of them privately so that following
4919allocations have no synchronization overhead. When the cache is full, the allocator
4920returns some cached nodes to the common pool, and those will be available to other
4921[classref boost::interprocess::cached_adaptive_pool cached_adaptive_pools] or
4922[classref boost::interprocess::adaptive_pool adaptive_pools] of the same managed segment.
4923
4924[*Equality:] Two [classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool]
4925instances constructed with the same segment manager compare equal. If an instance is
4926created using copy constructor, that instance compares equal with the original one.
4927
4928[*Allocation thread-safety:] Allocation and deallocation are [*not] thread-safe.
4929
4930To use [classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool],
4931you must include the following header:
4932
4933[c++]
4934
4935   #include <boost/interprocess/allocators/cached_adaptive_pool.hpp>
4936
4937[classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool]
4938has the following declaration:
4939
4940[c++]
4941
4942   namespace boost {
4943   namespace interprocess {
4944
4945   template<class T, class SegmentManager, std::size_t NodesPerChunk = ..., std::size_t MaxFreeNodes = ...>
4946   class cached_adaptive_pool;
4947
4948   }  //namespace interprocess {
4949   }  //namespace boost {
4950
4951A [classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool] instance
4952and an [classref boost::interprocess::adaptive_pool adaptive_pool] instance
4953share the same pool if both instances receive the same template parameters. This means
4954that nodes returned to the shared pool by one of them can be reused by the other.
4955Please note that this does not mean that both allocators compare equal, this is just
4956information for programmers that want to maximize the use of the pool.
4957
4958[classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool], offers
4959additional functions to control the cache (the cache can be controlled per instance):
4960
4961*  `void set_max_cached_nodes(std::size_t n)`: Sets the maximum cached nodes limit.
4962   If cached nodes reach the limit, some are returned to the shared pool.
4963
4964*  `std::size_t get_max_cached_nodes() const`: Returns the maximum cached nodes limit.
4965
4966*  `void deallocate_cache()`: Returns the cached nodes to the shared pool.
4967
4968An example using [classref boost::interprocess::cached_adaptive_pool cached_adaptive_pool]:
4969
4970[import ../example/doc_cached_adaptive_pool.cpp]
4971[doc_cached_adaptive_pool]
4972
4973[endsect]
4974
4975[endsect]
4976
4977[section:containers_explained Interprocess and containers in managed memory segments]
4978
4979[section:stl_container_requirements Container requirements for Boost.Interprocess allocators]
4980
4981[*Boost.Interprocess] STL compatible allocators offer a STL compatible allocator
4982interface and if they define their internal *pointer* typedef as a relative pointer,
4983they can be used to place STL containers in shared memory, memory mapped files or
4984in a user defined memory segment.
4985
4986However, as Scott Meyers mentions in his Effective STL
4987book, Item 10, ['"Be aware of allocator conventions and
4988restrictions"]:
4989
4990* ['"the Standard explicitly allows library implementers
4991to assume that every allocator's pointer typedef is
4992a synonym for T*"]
4993
4994* ['"the Standard says that an implementation of the STL is
4995permitted to assume that all allocator objects of the
4996same type are equivalent and always compare equal"]
4997
4998Obviously, if any STL implementation ignores pointer typedefs,
4999no smart pointer can be used as allocator::pointer. If STL
5000implementations assume all allocator objects of the same
5001type compare equal, it will assume that two allocators,
5002each one allocating from a different memory pool
5003are equal, which is a complete disaster.
5004
5005STL containers that we want to place in shared memory or memory
5006mapped files with [*Boost.Interprocess] can't make any of these assumptions, so:
5007
5008* STL containers may not assume that memory allocated with
5009  an allocator can be deallocated with other allocators of
5010  the same type. All allocators objects must compare equal
5011  only if memory allocated with one object can be deallocated
5012  with the other one, and this can only tested with
5013  operator==() at run-time.
5014
5015* Containers' internal pointers should be of the type allocator::pointer
5016  and containers may not assume allocator::pointer is a raw pointer.
5017
5018* All objects must be constructed-destroyed via
5019  allocator::construct and allocator::destroy functions.
5020
5021[endsect]
5022
5023[section:containers STL containers in managed memory segments]
5024
5025Unfortunately, many STL implementations use raw pointers
5026for internal data and ignore allocator pointer typedefs
5027and others suppose at some point that the allocator::typedef
5028is T*. This is because in practice,
5029there wasn't need of allocators with a pointer typedef
5030different from T* for pooled/node memory
5031allocators.
5032
5033Until STL implementations handle allocator::pointer typedefs
5034in a generic way, [*Boost.Interprocess] offers the following classes:
5035
5036*  [*boost:interprocess::vector] is the implementation of `std::vector` ready
5037   to be used in managed memory segments like shared memory. To use it include:
5038
5039[c++]
5040
5041   #include <boost/interprocess/containers/vector.hpp>
5042
5043*  [*boost:interprocess::deque] is the implementation of `std::deque` ready
5044   to be used in managed memory segments like shared memory. To use it include:
5045
5046[c++]
5047
5048   #include <boost/interprocess/containers/deque.hpp>
5049
5050*  [classref boost::interprocess::list list] is the implementation of `std::list` ready
5051   to be used in managed memory segments like shared memory. To use it include:
5052
5053[c++]
5054
5055   #include <boost/interprocess/containers/list.hpp>
5056
5057*  [classref boost::interprocess::slist slist] is the implementation of SGI's `slist` container (singly linked list) ready
5058   to be used in managed memory segments like shared memory. To use it include:
5059
5060[c++]
5061
5062   #include <boost/interprocess/containers/slist.hpp>
5063
5064*  [classref boost::interprocess::set set]/
5065   [classref boost::interprocess::multiset multiset]/
5066   [classref boost::interprocess::map map]/
5067   [classref boost::interprocess::multimap multimap] family is the implementation of
5068   std::set/multiset/map/multimap family ready
5069   to be used in managed memory segments like shared memory. To use them include:
5070
5071[c++]
5072
5073   #include <boost/interprocess/containers/set.hpp>
5074   #include <boost/interprocess/containers/map.hpp>
5075
5076*  [classref boost::interprocess::flat_set flat_set]/
5077   [classref boost::interprocess::flat_multiset flat_multiset]/
5078   [classref boost::interprocess::flat_map flat_map]/
5079   [classref boost::interprocess::flat_multimap flat_multimap] classes are the
5080   adaptation and extension of Andrei Alexandrescu's famous AssocVector class
5081   from Loki library, ready for the shared memory. These classes offer the same
5082   functionality as `std::set/multiset/map/multimap` implemented with an ordered vector,
5083   which has faster lookups than the standard ordered associative containers
5084   based on red-black trees, but slower insertions. To use it include:
5085
5086[c++]
5087
5088   #include <boost/interprocess/containers/flat_set.hpp>
5089   #include <boost/interprocess/containers/flat_map.hpp>
5090
5091*  [classref boost::interprocess::basic_string basic_string]
5092   is the implementation of `std::basic_string` ready
5093   to be used in managed memory segments like shared memory.
5094   It's implemented using a vector-like contiguous storage, so
5095   it has fast c string conversion and can be used with the
5096   [link interprocess.streams.vectorstream vectorstream] iostream formatting classes.
5097   To use it include:
5098
5099[c++]
5100
5101   #include <boost/interprocess/containers/string.hpp>
5102
5103All these containers have the same default arguments as standard
5104containers and they can be used with other, non [*Boost.Interprocess]
5105allocators (std::allocator, or boost::pool_allocator, for example).
5106
5107To place any of these containers in managed memory segments, we must
5108define the allocator template parameter with a [*Boost.Interprocess] allocator
5109so that the container allocates the values in the managed memory segment.
5110To place the container itself in shared memory, we construct it
5111in the managed memory segment just like any other object with [*Boost.Interprocess]:
5112
5113[import ../example/doc_cont.cpp]
5114[doc_cont]
5115
5116These containers also show how easy is to create/modify
5117an existing container making possible to place it in shared memory.
5118
5119[endsect]
5120
5121[section:where_allocate Where is this being allocated?]
5122
5123[*Boost.Interprocess] containers are placed in shared memory/memory mapped files,
5124etc... using two mechanisms [*at the same time]:
5125
5126*  [*Boost.Interprocess ]`construct<>`, `find_or_construct<>`... functions. These
5127   functions place a C++ object in the shared memory/memory mapped file. But this
5128   places only the object, but *not* the memory that this object may allocate dynamically.
5129
5130*  Shared memory allocators. These allow allocating shared memory/memory mapped file
5131   portions so that containers can allocate dynamically fragments of memory to store
5132   newly inserted elements.
5133
5134This means that to place any [*Boost.Interprocess] container (including
5135[*Boost.Interprocess] strings) in shared memory or memory mapped files,
5136containers *must*:
5137
5138* Define their template allocator parameter to a [*Boost.Interprocess] allocator.
5139
5140* Every container constructor must take the [*Boost.Interprocess] allocator as parameter.
5141
5142* You must use construct<>/find_or_construct<>... functions to place the container
5143  in the managed memory.
5144
5145If you do the first two points but you don't use `construct<>` or `find_or_construct<>`
5146you are creating a container placed *only* in your process but that allocates memory
5147for contained types from shared memory/memory mapped file.
5148
5149Let's see an example:
5150
5151[import ../example/doc_where_allocate.cpp]
5152[doc_where_allocate]
5153
5154[endsect]
5155
5156[section:containers_and_move Move semantics in Interprocess containers]
5157
5158[*Boost.Interprocess] containers support move semantics, which means that the contents
5159of a container can be moved from a container to another one, without any copying. The
5160contents of the source container are transferred to the target container and the source
5161container is left in default-constructed state.
5162
5163When using containers of containers, we can also use move-semantics to insert
5164objects in the container, avoiding unnecessary copies.
5165
5166
5167To transfer the contents of a container to another one, use
5168`boost::move()` function, as shown in the example. For more details
5169about functions supporting move-semantics, see the reference section of
5170Boost.Interprocess containers:
5171
5172[import ../example/doc_move_containers.cpp]
5173[doc_move_containers]
5174
5175[endsect]
5176
5177[section:containers_of_containers Containers of containers]
5178
5179When creating containers of containers, each container needs an allocator.
5180To avoid using several allocators with complex type definitions, we can take
5181advantage of the type erasure provided by void allocators and the ability
5182to implicitly convert void allocators in allocators that allocate other types.
5183
5184Here we have an example that builds a map in shared memory. Key is a string
5185and the mapped type is a class that stores several containers:
5186
5187[import ../example/doc_complex_map.cpp]
5188[doc_complex_map]
5189
5190[endsect]
5191
5192[endsect]
5193
5194[section:additional_containers Boost containers compatible with Boost.Interprocess]
5195
5196As mentioned, container developers might need to change their implementation to make them
5197compatible with Boost.Interprocess, because implementation usually ignore allocators with
5198smart pointers. Hopefully several Boost containers are compatible with [*Interprocess].
5199
5200[section:unordered Boost unordered containers]
5201
5202[*Boost.Unordered] containers are compatible with Interprocess, so programmers can store
5203hash containers in shared memory and memory mapped files. Here is a small example storing
5204`unordered_map` in shared memory:
5205
5206[import ../example/doc_unordered_map.cpp]
5207[doc_unordered_map]
5208
5209[endsect]
5210
5211[section:multi_index Boost.MultiIndex containers]
5212
5213The widely used [*Boost.MultiIndex] library is compatible with [*Boost.Interprocess] so
5214we can construct pretty good databases in shared memory. Constructing databases in shared
5215memory is a bit tougher than in normal memory, usually because those databases contain strings
5216and those strings need to be placed in shared memory. Shared memory strings require
5217an allocator in their constructors so this usually makes object insertion a bit more
5218complicated.
5219
5220Here is an example that shows how to put a multi index container in shared memory:
5221
5222[import ../example/doc_multi_index.cpp]
5223[doc_multi_index]
5224
5225[endsect]
5226
5227Programmers can place [*Boost.CircularBuffer] containers in sharecd memory provided
5228they disable debugging facilities with defines `BOOST_CB_DISABLE_DEBUG` or the more
5229general `NDEBUG`. The reason is that those debugging facilities are only compatible
5230with raw pointers.
5231
5232[endsect]
5233
5234[endsect]
5235
5236[section:memory_algorithms Memory allocation algorithms]
5237
5238[section:simple_seq_fit simple_seq_fit: A simple shared memory management algorithm]
5239
5240The algorithm is a variation of sequential fit using singly
5241linked list of free memory buffers. The algorithm is based
5242on the article about shared memory titled
5243[@http://home.earthlink.net/~joshwalker1/writing/SharedMemory.html ['"Taming Shared Memory"] ].
5244The algorithm is as follows:
5245
5246The shared memory is divided in blocks of free shared memory,
5247each one with some control data and several bytes of memory
5248ready to be used. The control data contains a pointer (in
5249our case offset_ptr) to the next free block and the size of
5250the block. The allocator consists of a singly linked list
5251of free blocks, ordered by address. The last block, points
5252always to the first block:
5253
5254[c++]
5255
5256   simple_seq_fit memory layout:
5257
5258       main      extra  allocated  free_block_1     allocated   free_block_2    allocated   free_block_3
5259       header    header  block       ctrl     usr     block      ctrl     usr     block      ctrl     usr
5260      _________  _____  _________  _______________  _________  _______________  _________  _______________
5261     |         ||     ||         ||         |     ||         ||         |     ||         ||         |     |
5262     |free|ctrl||extra||         ||next|size| mem ||         ||next|size| mem ||         ||next|size| mem |
5263     |_________||_____||_________||_________|_____||_________||_________|_____||_________||_________|_____|
5264         |                         | |                         |  |                       | |
5265         |_>_>_>_>_>_>_>_>_>_>_>_>_| |_>_>_>_>_>_>_>_>_>_>_>_>_|  |_>_>_>_>_>_>_>_>_>_>_>_| |
5266                                   |                                                        |
5267                                   |_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<_<__|
5268
5269When a user requests N bytes of memory, the allocator
5270traverses the free block list looking for a block large
5271enough. If the "mem" part of the block has the same
5272size as the requested memory, we erase the block from
5273the list and return a pointer to the "mem" part of the
5274block. If the "mem" part size is bigger than needed,
5275we split the block in two blocks, one of the requested
5276size and the other with remaining size. Now, we take
5277the block with the exact size, erase it from list and
5278give it to the user.
5279
5280When the user deallocates a block, we traverse the list (remember
5281that the list is ordered), and search its place depending on
5282the block address. Once found, we try to merge the block with
5283adjacent blocks if possible.
5284
5285To ease implementation, the size of the free memory block
5286is measured in multiples of "basic_size" bytes.  The basic
5287size will be the size of the control block aligned to
5288machine most restrictive alignment.
5289
5290This algorithm is a low size overhead algorithm suitable for simple allocation
5291schemes. This algorithm should only be used when size is a major concern, because
5292the performance of this algorithm suffers when the memory is fragmented. This
5293algorithm has linear allocation and deallocation time, so when the number
5294of allocations is high, the user should use a more performance-friendly algorithm.
5295
5296In most 32 systems, with 8 byte alignment, "basic_size" is 8 bytes.
5297This means that an allocation request of 1 byte leads to
5298the creation of a 16 byte block, where 8 bytes are available to the user.
5299The allocation of 8 bytes leads also to the same 16 byte block.
5300
5301[endsect]
5302
5303[section:rbtree_best_fit rbtree_best_fit: Best-fit logarithmic-time complexity allocation]
5304
5305This algorithm is an advanced algorithm using red-black trees to sort the free
5306portions of the memory segment by size. This allows logarithmic complexity
5307allocation. Apart from this, a doubly-linked list of all portions of memory
5308(free and allocated) is maintained to allow  constant-time access to previous
5309and next blocks when doing merging operations.
5310
5311The data used to create the red-black tree of free nodes is overwritten by the user
5312since it's no longer used once the memory is allocated. This maintains the memory
5313size overhead down to the doubly linked list overhead, which is pretty small (two pointers).
5314Basically this is the scheme:
5315
5316[c++]
5317
5318   rbtree_best_fit memory layout:
5319
5320      main            allocated block   free block                        allocated block  free block
5321      header
5322     _______________  _______________  _________________________________  _______________  _________________________________
5323    |               ||         |     ||         |                 |     ||         |     ||         |                 |     |
5324    |  main header  ||next|prev| mem ||next|prev|left|right|parent| mem ||next|prev| mem ||next|prev|left|right|parent| mem |
5325    |_______________||_________|_____||_________|_________________|_____||_________|_____||_________|_________________|_____|
5326
5327
5328This allocation algorithm is pretty fast and scales well with big shared memory
5329segments and big number of allocations. To form a block a minimum memory size is needed:
5330the sum of the doubly linked list and the red-black tree control data.
5331The size of a block is measured in multiples of the most restrictive alignment value.
5332
5333In most 32 systems with 8 byte alignment the minimum size of a block is 24 byte.
5334When a block is allocated the control data related to the red black tree
5335is overwritten by the user (because it's only needed for free blocks).
5336
5337In those systems a 1 byte allocation request means that:
5338
5339*  24 bytes of memory from the segment are used to form a block.
5340*  16 bytes of them are usable for the user.
5341
5342For really small allocations (<= 8 bytes), this algorithm wastes more memory than the
5343simple sequential fit algorithm (8 bytes more).
5344For allocations bigger than 8 bytes the memory overhead is exactly the same.
5345This is the default allocation algorithm in [*Boost.Interprocess] managed memory
5346segments.
5347
5348[endsect]
5349
5350[endsect]
5351
5352[section:streams Direct iostream formatting: vectorstream and bufferstream]
5353
5354Shared memory, memory-mapped files and all [*Boost.Interprocess] mechanisms are focused
5355on efficiency. The reason why shared memory is used is that it's the
5356fastest IPC mechanism available. When passing text-oriented messages through
5357shared memory, there is need to format the message. Obviously C++ offers
5358the iostream framework for that work.
5359
5360Some programmers appreciate the iostream safety and design for memory
5361formatting but feel that the stringstream family is far from efficient not
5362when formatting, but when obtaining formatted data to a string, or when
5363setting the string from which the stream will extract data. An example:
5364
5365[c++]
5366
5367   //Some formatting elements
5368   std::string my_text = "...";
5369   int number;
5370
5371   //Data reader
5372   std::istringstream input_processor;
5373
5374   //This makes a copy of the string. If not using a
5375   //reference counted string, this is a serious overhead.
5376   input_processor.str(my_text);
5377
5378   //Extract data
5379   while(/*...*/){
5380      input_processor >> number;
5381   }
5382
5383   //Data writer
5384   std::ostringstream output_processor;
5385
5386   //Write data
5387   while(/*...*/){
5388      output_processor << number;
5389   }
5390
5391   //This returns a temporary string. Even with return-value
5392   //optimization this is expensive.
5393   my_text = input_processor.str();
5394
5395The problem is even worse if the string is a shared-memory string, because
5396to extract data, we must copy the data first from shared-memory to a
5397`std::string` and then to a `std::stringstream`. To encode data in a shared memory
5398string we should copy data from a `std::stringstream` to a `std::string` and then
5399to the shared-memory string.
5400
5401Because of this overhead, [*Boost.Interprocess] offers a way to format memory-strings
5402(in shared memory, memory mapped files or any other memory segment) that
5403can avoid all unneeded string copy and memory allocation/deallocations, while
5404using all iostream facilities. [*Boost.Interprocess] *vectorstream* and *bufferstream* implement
5405vector-based and fixed-size buffer based storage support for iostreams and
5406all the formatting/locale hard work is done by standard `std::basic_streambuf<>`
5407and `std::basic_iostream<>` classes.
5408
5409[section:vectorstream Formatting directly in your character vector: vectorstream]
5410
5411The *vectorstream* class family (*basic_vectorbuf*, *basic_ivectorstream*
5412,*basic_ovectorstream* and *basic_vectorstream*) is an efficient way to obtain
5413formatted reading/writing directly in a character vector. This way, if
5414a shared-memory vector is used, data is extracted/written from/to the shared-memory
5415vector, without additional copy/allocation. We can see the declaration of
5416basic_vectorstream here:
5417
5418   //!A basic_iostream class that holds a character vector specified by CharVector
5419   //!template parameter as its formatting buffer. The vector must have
5420   //!contiguous storage, like std::vector, boost::interprocess::vector or
5421   //!boost::interprocess::basic_string
5422   template <class CharVector, class CharTraits =
5423            std::char_traits<typename CharVector::value_type> >
5424   class basic_vectorstream
5425   : public std::basic_iostream<typename CharVector::value_type, CharTraits>
5426
5427   {
5428      public:
5429      typedef CharVector                                                   vector_type;
5430      typedef typename std::basic_ios
5431         <typename CharVector::value_type, CharTraits>::char_type          char_type;
5432      typedef typename std::basic_ios<char_type, CharTraits>::int_type     int_type;
5433      typedef typename std::basic_ios<char_type, CharTraits>::pos_type     pos_type;
5434      typedef typename std::basic_ios<char_type, CharTraits>::off_type     off_type;
5435      typedef typename std::basic_ios<char_type, CharTraits>::traits_type  traits_type;
5436
5437      //!Constructor. Throws if vector_type default constructor throws.
5438      basic_vectorstream(std::ios_base::openmode mode
5439                        = std::ios_base::in | std::ios_base::out);
5440
5441      //!Constructor. Throws if vector_type(const Parameter &param) throws.
5442      template<class Parameter>
5443      basic_vectorstream(const Parameter &param, std::ios_base::openmode mode
5444                        = std::ios_base::in | std::ios_base::out);
5445
5446      ~basic_vectorstream(){}
5447
5448      //!Returns the address of the stored stream buffer.
5449      basic_vectorbuf<CharVector, CharTraits>* rdbuf() const;
5450
5451      //!Swaps the underlying vector with the passed vector.
5452      //!This function resets the position in the stream.
5453      //!Does not throw.
5454      void swap_vector(vector_type &vect);
5455
5456      //!Returns a const reference to the internal vector.
5457      //!Does not throw.
5458      const vector_type &vector() const;
5459
5460      //!Preallocates memory from the internal vector.
5461      //!Resets the stream to the first position.
5462      //!Throws if the internals vector's memory allocation throws.
5463      void reserve(typename vector_type::size_type size);
5464   };
5465
5466The vector type is templatized, so that we can use any type of vector:
5467[*std::vector], [classref boost::interprocess::vector]... But the storage must be *contiguous*,
5468we can't use a deque. We can even use *boost::interprocess::basic_string*, since it has a
5469vector interface and it has contiguous storage. *We can't use std::string*, because
5470although some std::string implementation are vector-based, others can have
5471optimizations and reference-counted implementations.
5472
5473The user can obtain a const reference to the internal vector using
5474`vector_type vector() const` function and he also can swap the internal vector
5475with an external one calling `void swap_vector(vector_type &vect)`.
5476The swap function resets the stream position.
5477This functions allow efficient methods to obtain the formatted data avoiding
5478all allocations and data copies.
5479
5480Let's see an example to see how to use vectorstream:
5481
5482[import ../example/doc_vectorstream.cpp]
5483[doc_vectorstream]
5484
5485[endsect]
5486
5487[section:bufferstream Formatting directly in your character buffer: bufferstream]
5488
5489As seen, vectorstream offers an easy and secure way for efficient iostream
5490formatting, but many times, we have to read or write formatted data from/to a
5491fixed size character buffer (a static buffer, a c-string, or any other).
5492Because of the overhead of stringstream, many developers (specially in
5493embedded systems) choose sprintf family. The *bufferstream* classes offer
5494iostream interface with direct formatting in a fixed size memory buffer with
5495protection against buffer overflows. This is the interface:
5496
5497   //!A basic_iostream class that uses a fixed size character buffer
5498   //!as its formatting buffer.
5499   template <class CharT, class CharTraits = std::char_traits<CharT> >
5500   class basic_bufferstream
5501      : public std::basic_iostream<CharT, CharTraits>
5502
5503   {
5504      public:                         // Typedefs
5505      typedef typename std::basic_ios
5506         <CharT, CharTraits>::char_type          char_type;
5507      typedef typename std::basic_ios<char_type, CharTraits>::int_type     int_type;
5508      typedef typename std::basic_ios<char_type, CharTraits>::pos_type     pos_type;
5509      typedef typename std::basic_ios<char_type, CharTraits>::off_type     off_type;
5510      typedef typename std::basic_ios<char_type, CharTraits>::traits_type  traits_type;
5511
5512      //!Constructor. Does not throw.
5513      basic_bufferstream(std::ios_base::openmode mode
5514                        = std::ios_base::in | std::ios_base::out);
5515
5516      //!Constructor. Assigns formatting buffer. Does not throw.
5517      basic_bufferstream(CharT *buffer, std::size_t length,
5518                        std::ios_base::openmode mode
5519                           = std::ios_base::in | std::ios_base::out);
5520
5521      //!Returns the address of the stored stream buffer.
5522      basic_bufferbuf<CharT, CharTraits>* rdbuf() const;
5523
5524      //!Returns the pointer and size of the internal buffer.
5525      //!Does not throw.
5526      std::pair<CharT *, std::size_t> buffer() const;
5527
5528      //!Sets the underlying buffer to a new value. Resets
5529      //!stream position. Does not throw.
5530      void buffer(CharT *buffer, std::size_t length);
5531   };
5532
5533   //Some typedefs to simplify usage
5534   typedef basic_bufferstream<char>     bufferstream;
5535   typedef basic_bufferstream<wchar_t>  wbufferstream;
5536   // ...
5537
5538While reading from a fixed size buffer, *bufferstream* activates endbit flag if
5539we try to read an address beyond the end of the buffer. While writing to a
5540fixed size buffer, *bufferstream* will active the badbit flag if a buffer overflow
5541is going to happen and disallows writing. This way, the fixed size buffer
5542formatting through *bufferstream* is secure and efficient, and offers a good
5543alternative to sprintf/sscanf functions. Let's see an example:
5544
5545[import ../example/doc_bufferstream.cpp]
5546[doc_bufferstream]
5547
5548As seen, *bufferstream* offers an efficient way to format data without any
5549allocation and extra copies. This is very helpful in embedded systems, or
5550formatting inside time-critical loops, where stringstream extra copies would
5551be too expensive. Unlike sprintf/sscanf, it has protection against buffer
5552overflows. As we know, according to the *Technical Report on C++ Performance*,
5553it's possible to design efficient iostreams for embedded platforms, so this
5554bufferstream class comes handy to format data to stack, static or shared memory
5555buffers.
5556
5557[endsect]
5558
5559[endsect]
5560
5561[section:interprocess_smart_ptr Ownership smart pointers]
5562
5563C++ users know the importance of ownership smart pointers when dealing with resources.
5564Boost offers a wide range of such type of pointers: `intrusive_ptr<>`,
5565`scoped_ptr<>`, `shared_ptr<>`...
5566
5567When building complex shared memory/memory mapped files structures, programmers
5568would like to use also the advantages of these smart pointers. The problem is that
5569Boost and C++ TR1 smart pointers are not ready to be used for shared memory. The cause
5570is that those smart pointers contain raw pointers and they use virtual functions,
5571something that is not possible if you want to place your data in shared memory.
5572The virtual function limitation makes even impossible to achieve the same level of
5573functionality of Boost and TR1 with [*Boost.Interprocess] smart pointers.
5574
5575Interprocess ownership smart pointers are mainly "smart pointers containing smart pointers",
5576so we can specify the pointer type they contain.
5577
5578[section:intrusive_ptr Intrusive pointer]
5579
5580[classref boost::interprocess::intrusive_ptr] is the generalization of `boost::intrusive_ptr<>`
5581to allow non-raw pointers as intrusive pointer members. As the well-known
5582`boost::intrusive_ptr` we must specify the pointee type but we also must also specify
5583the pointer type to be stored in the intrusive_ptr:
5584
5585[c++]
5586
5587   //!The intrusive_ptr class template stores a pointer to an object
5588   //!with an embedded reference count. intrusive_ptr is parameterized on
5589   //!T (the type of the object pointed to) and VoidPointer(a void pointer type
5590   //!that defines the type of pointer that intrusive_ptr will store).
5591   //!intrusive_ptr<T, void *> defines a class with a T* member whereas
5592   //!intrusive_ptr<T, offset_ptr<void> > defines a class with a offset_ptr<T> member.
5593   //!Relies on unqualified calls to:
5594   //!
5595   //!void intrusive_ptr_add_ref(T * p);
5596   //!void intrusive_ptr_release(T * p);
5597   //!
5598   //!with (p != 0)
5599   //!
5600   //!The object is responsible for destroying itself.
5601   template<class T, class VoidPointer>
5602   class intrusive_ptr;
5603
5604So `boost::interprocess::intrusive_ptr<MyClass, void*>` is equivalent to
5605`boost::intrusive_ptr<MyClass>`. But if we want to place the intrusive_ptr in
5606shared memory we must specify a relative pointer type like
5607`boost::interprocess::intrusive_ptr<MyClass, boost::interprocess::offset_ptr<void> >`
5608
5609[import ../example/doc_intrusive.cpp]
5610[doc_intrusive]
5611
5612[endsect]
5613
5614[section:scoped_ptr Scoped pointer]
5615
5616`boost::interprocess::scoped_ptr<>` is the big brother of `boost::scoped_ptr<>`, which
5617adds a custom deleter to specify how the pointer passed to the scoped_ptr must be destroyed.
5618Also, the `pointer` typedef of the deleter will specify the pointer type stored by scoped_ptr.
5619
5620[c++]
5621
5622   //!scoped_ptr stores a pointer to a dynamically allocated object.
5623   //!The object pointed to is guaranteed to be deleted, either on destruction
5624   //!of the scoped_ptr, or via an explicit reset. The user can avoid this
5625   //!deletion using release().
5626   //!scoped_ptr is parameterized on T (the type of the object pointed to) and
5627   //!Deleter (the functor to be executed to delete the internal pointer).
5628   //!The internal pointer will be of the same pointer type as typename
5629   //!Deleter::pointer type (that is, if typename Deleter::pointer is
5630   //!offset_ptr<void>, the internal pointer will be offset_ptr<T>).
5631   template<class T, class Deleter>
5632   class scoped_ptr;
5633
5634`scoped_ptr<>` comes handy to implement *rollbacks* with exceptions: if an exception
5635is thrown or we call `return` in the scope of `scoped_ptr<>` the deleter is
5636automatically called so that *the deleter can be considered as a rollback* function.
5637If all goes well, we call `release()` member function to avoid rollback when
5638the `scoped_ptr` goes out of scope.
5639
5640[import ../example/doc_scoped_ptr.cpp]
5641[doc_scoped_ptr]
5642
5643[endsect]
5644
5645[section:shared_ptr Shared pointer and weak pointer]
5646
5647[*Boost.Interprocess] also offers the possibility of creating non-intrusive
5648reference-counted objects in managed shared memory or mapped files.
5649
5650Unlike
5651[@http://www.boost.org/libs/smart_ptr/shared_ptr.htm boost::shared_ptr],
5652due to limitations of mapped segments [classref boost::interprocess::shared_ptr]
5653cannot take advantage of virtual functions to maintain the same shared pointer
5654type while providing user-defined allocators and deleters. The allocator
5655and the deleter are template parameters of the shared pointer.
5656
5657Since the reference count and other auxiliary data needed by
5658[classref boost::interprocess::shared_ptr shared_ptr] must be created also in
5659the managed segment, and the deleter has to delete the object from
5660the segment, the user must specify an allocator object and a deleter object
5661when constructing a non-empty instance of
5662[classref boost::interprocess::shared_ptr shared_ptr], just like
5663[*Boost.Interprocess] containers need to pass allocators in their constructors.
5664
5665Here is the declaration of [classref boost::interprocess::shared_ptr shared_ptr]:
5666
5667[c++]
5668
5669   template<class T, class VoidAllocator, class Deleter>
5670   class shared_ptr;
5671
5672*  T is the type of the pointed type.
5673*  VoidAllocator is the allocator to be used to allocate auxiliary
5674   elements such as the reference count, the deleter...
5675   The internal `pointer` typedef of the allocator will determine
5676   the type of pointer that shared_ptr will internally use, so
5677   allocators defining `pointer` as `offset_ptr<void>` will
5678   make all internal pointers used by `shared_ptr` to be
5679   also relative pointers. See [classref boost::interprocess::allocator]
5680   for a working allocator.
5681*  Deleter is the function object that will be used to destroy
5682   the pointed object when the last reference to the object
5683   is destroyed. The deleter functor will take a pointer to T
5684   of the same category as the void pointer defined by
5685   `VoidAllocator::pointer`. See [classref boost::interprocess::deleter]
5686   for a generic deleter that erases a object from a managed segment.
5687
5688With correctly specified parameters, [*Boost.Interprocess] users
5689can create objects in shared memory that hold shared pointers pointing
5690to other objects also in shared memory, obtaining the benefits of
5691reference counting. Let's see how to create a shared pointer in a managed shared memory:
5692
5693[import ../example/doc_shared_ptr_explicit.cpp]
5694[doc_shared_ptr_explicit]
5695
5696[classref boost::interprocess::shared_ptr] is very flexible and
5697configurable (we can specify the allocator and the deleter, for example),
5698but as shown the creation of a shared pointer in managed segments
5699need too much typing.
5700
5701To simplify this usage, [classref boost::interprocess::shared_ptr] header
5702offers a shared pointer definition helper class
5703([classref boost::interprocess::managed_shared_ptr managed_shared_ptr]) and a function
5704([funcref boost::interprocess::make_managed_shared_ptr make_managed_shared_ptr])
5705to easily construct a shared pointer from a type allocated in a managed segment
5706with an allocator that will allocate the reference count also in the managed
5707segment and a deleter that will erase the object from the segment.
5708
5709These utilities will use a [*Boost.Interprocess] allocator
5710([classref boost::interprocess::allocator])
5711and deleter ([classref boost::interprocess::deleter]) to do their job.
5712The definition of the previous shared pointer
5713could be simplified to the following:
5714
5715[c++]
5716
5717   typedef managed_shared_ptr<MyType, managed_shared_memory>::type my_shared_ptr;
5718
5719And the creation of a shared pointer can be simplified to this:
5720
5721[c++]
5722
5723   my_shared_ptr sh_ptr = make_managed_shared_ptr
5724      (segment.construct<MyType>("object to share")(), segment);
5725
5726[*Boost.Interprocess] also offers a weak pointer named
5727[classref boost::interprocess::weak_ptr weak_ptr] (with its corresponding
5728[classref boost::interprocess::managed_weak_ptr managed_weak_ptr] and
5729[funcref boost::interprocess::make_managed_weak_ptr make_managed_weak_ptr] utilities)
5730to implement non-owning observers of an object owned by
5731[classref boost::interprocess::shared_ptr shared_ptr].
5732
5733Now let's see a detailed example of the use of
5734[classref boost::interprocess::shared_ptr shared_ptr]:
5735and
5736[classref boost::interprocess::weak_ptr weak_ptr]
5737
5738[import ../example/doc_shared_ptr.cpp]
5739[doc_shared_ptr]
5740
5741In general, using [*Boost.Interprocess]' [classref boost::interprocess::shared_ptr shared_ptr]
5742and [classref boost::interprocess::weak_ptr weak_ptr] is very similar to their
5743counterparts [@http://www.boost.org/libs/smart_ptr/shared_ptr.htm boost::shared_ptr]
5744and [@http://www.boost.org/libs/smart_ptr/weak_ptr.htm boost::weak_ptr], but
5745they need more template parameters and more run-time parameters in their constructors.
5746
5747Just like [@http://www.boost.org/libs/smart_ptr/shared_ptr.htm boost::shared_ptr]
5748can be stored in a STL container, [classref boost::interprocess::shared_ptr shared_ptr]
5749can also be stored in [*Boost.Interprocess] containers.
5750
5751If a programmer just uses [classref boost::interprocess::shared_ptr shared_ptr]
5752to be able to insert dynamically constructed objects into a container constructed
5753in the managed segment, but he does not need to share the ownership of that object with
5754other objects [classref boost::interprocess::managed_unique_ptr managed_unique_ptr] is a much
5755faster and easier to use alternative.
5756
5757[endsect]
5758
5759[section:unique_ptr Unique pointer]
5760
5761Unique ownership smart pointers are really useful to free programmers from
5762manual resource liberation of non-shared objects. [*Boost.Interprocess]'
5763`unique_ptr` is much like
5764[classref boost::interprocess::scoped_ptr scoped_ptr] but it's [*moveable]
5765and can be easily inserted in [*Boost.Interprocess] containers.
5766Interprocess had its own `unique_ptr` implementation but from Boost 1.57,
5767[*Boost.Interprocess] uses the improved and generic `boost::unique_ptr`
5768implementation. Here is the declaration of the unique pointer class:
5769
5770[c++]
5771
5772   template <class T, class D>
5773   class unique_ptr;
5774
5775*  T is the type of the object pointed by `unique_ptr`.
5776*  D is the deleter that will erase the object type of the object pointed by
5777   the unique_ptr when the unique pointer
5778   is destroyed (and if still has the ownership of the object). If the deleter defines
5779   an internal `pointer` typedef, `unique_ptr`]
5780   will use an internal pointer of the same type. So if `D::pointer` is `offset_ptr<T>`
5781   the unique pointer will store a relative pointer instead of a raw one. This
5782   allows placing `unique_ptr` in shared
5783   memory and memory-mapped files.
5784
5785`unique_ptr` can release the ownership of
5786the stored pointer so it's useful also to be used as a rollback function. One of the main
5787properties of the class is that [*is not copyable, but only moveable]. When a unique
5788pointer is moved to another one, the ownership of the pointer is transferred from
5789the source unique pointer to the target unique pointer. If the target unique pointer
5790owned an object, that object is first deleted before taking ownership of the new object.
5791
5792[*Boost.Interprocess] also offers auxiliary types to
5793easily define and construct unique pointers that can be placed in managed segments
5794and will correctly delete owned object from the segment:
5795[classref boost::interprocess::managed_unique_ptr managed_unique_ptr]
5796and
5797[funcref boost::interprocess::make_managed_unique_ptr make_managed_unique_ptr]
5798utilities.
5799
5800Here we see an example of the use `unique_ptr`
5801including creating containers of such objects:
5802
5803[import ../example/doc_unique_ptr.cpp]
5804[doc_unique_ptr]
5805
5806[endsect]
5807
5808[endsect]
5809
5810[section:architecture Architecture and internals]
5811
5812[section:basic_guidelines Basic guidelines]
5813
5814When building [*Boost.Interprocess] architecture, I took some basic guidelines that can be
5815summarized by these points:
5816
5817*  [*Boost.Interprocess] should be portable at least in UNIX and Windows systems. That
5818   means unifying not only interfaces but also behaviour. This is why
5819   [*Boost.Interprocess] has chosen kernel or filesystem persistence for shared memory
5820   and named synchronization mechanisms. Process persistence for shared memory is also
5821   desirable but it's difficult to achieve in UNIX systems.
5822
5823*  [*Boost.Interprocess] inter-process synchronization primitives should be equal to thread
5824   synchronization primitives. [*Boost.Interprocess] aims to have an interface compatible
5825   with the C++ standard thread API.
5826
5827*  [*Boost.Interprocess] architecture should be modular, customizable but efficient. That's
5828   why [*Boost.Interprocess] is based on templates and memory algorithms, index types,
5829   mutex types and other classes are templatizable.
5830
5831*  [*Boost.Interprocess] architecture should allow the same concurrency as thread based
5832   programming. Different mutual exclusion levels are defined so that a process
5833   can concurrently allocate raw memory when expanding a shared memory vector while another
5834   process can be safely searching a named object.
5835
5836*  [*Boost.Interprocess] containers know nothing about [*Boost.Interprocess]. All specific
5837   behaviour is contained in the STL-like allocators. That allows STL vendors to slightly
5838   modify (or better said, generalize) their standard container implementations and obtain
5839   a fully std::allocator and boost::interprocess::allocator compatible container. This also
5840   make [*Boost.Interprocess] containers compatible with standard algorithms.
5841
5842[*Boost.Interprocess] is built above 3 basic classes: a [*memory algorithm], a
5843[*segment manager] and a [*managed memory segment]:
5844
5845[endsect]
5846
5847[section:architecture_algorithm_to_managed From the memory algorithm to the managed segment]
5848
5849[section:architecture_memory_algorithm The memory algorithm]
5850
5851The [*memory algorithm] is an object that is placed in the first bytes of a
5852shared memory/memory mapped file segment. The [*memory algorithm] can return
5853portions of that segment to users marking them as used and the user can return those
5854portions to the [*memory algorithm] so that the [*memory algorithm] mark them as free
5855again. There is an exception though: some bytes beyond the end of the memory
5856algorithm object, are reserved and can't be used for this dynamic allocation.
5857This "reserved" zone will be used to place other additional objects
5858in a well-known place.
5859
5860To sum up, a [*memory algorithm] has the same mission as malloc/free of
5861standard C library, but it just can return portions of the segment
5862where it is placed. The layout of a memory segment would be:
5863
5864[c++]
5865
5866   Layout of the memory segment:
5867    ____________ __________ ____________________________________________
5868   |            |          |                                            |
5869   |   memory   | reserved |  The memory algorithm will return portions |
5870   | algorithm  |          |  of the rest of the segment.               |
5871   |____________|__________|____________________________________________|
5872
5873
5874The [*memory algorithm] takes care of memory synchronizations, just like malloc/free
5875guarantees that two threads can call malloc/free at the same time. This is usually
5876achieved placing a process-shared mutex as a member of the memory algorithm. Take
5877in care that the memory algorithm knows [*nothing] about the segment (if it is
5878shared memory, a shared memory file, etc.). For the memory algorithm the segment
5879is just a fixed size memory buffer.
5880
5881The [*memory algorithm] is also a configuration point for the rest of the
5882[*Boost.Interprocess]
5883framework since it defines two basic types as member typedefs:
5884
5885[c++]
5886
5887   typedef /*implementation dependent*/ void_pointer;
5888   typedef /*implementation dependent*/ mutex_family;
5889
5890
5891The `void_pointer` typedef defines the pointer type that will be used in the
5892[*Boost.Interprocess] framework (segment manager, allocators, containers). If the memory
5893algorithm is ready to be placed in a shared memory/mapped file mapped in different base
5894addresses, this pointer type will be defined as `offset_ptr<void>` or a similar relative
5895pointer. If the [*memory algorithm] will be used just with fixed address mapping,
5896`void_pointer` can be defined as `void*`.
5897
5898The rest of the interface of a [*Boost.Interprocess] [*memory algorithm] is described in
5899[link interprocess.customizing_interprocess.custom_interprocess_alloc Writing a new shared memory allocation algorithm]
5900section. As memory algorithm examples, you can see the implementations
5901[classref boost::interprocess::simple_seq_fit  simple_seq_fit] or
5902[classref boost::interprocess::rbtree_best_fit rbtree_best_fit] classes.
5903
5904[endsect]
5905
5906[section:architecture_segment_manager The segment manager]
5907
5908The *segment manager*, is an object also placed in the first bytes of the
5909managed memory segment (shared memory, memory mapped file), that offers more
5910sophisticated services built above the [*memory algorithm]. How can [*both] the
5911segment manager and memory algorithm be placed in the beginning of the segment?
5912That's because the segment manager [*owns] the memory algorithm: The
5913truth is that the memory algorithm is [*embedded] in the segment manager:
5914
5915
5916[c++]
5917
5918   The layout of managed memory segment:
5919    _______ _________________
5920   |       |         |       |
5921   | some  | memory  | other |<- The memory algorithm considers
5922   |members|algorithm|members|   "other members" as reserved memory, so
5923   |_______|_________|_______|   it does not use it for dynamic allocation.
5924   |_________________________|____________________________________________
5925   |                         |                                            |
5926   |    segment manager      |  The memory algorithm will return portions |
5927   |                         |  of the rest of the segment.               |
5928   |_________________________|____________________________________________|
5929
5930
5931The [*segment manager] initializes the memory algorithm and tells the memory
5932manager that it should not use the memory where the rest of the
5933[*segment manager]'s member are placed for dynamic allocations. The
5934other members of the [*segment manager] are [*a recursive mutex]
5935(defined by the memory algorithm's [*mutex_family::recursive_mutex] typedef member),
5936and [*two indexes (maps)]: one to implement named allocations, and another one to
5937implement "unique instance" allocations.
5938
5939*  The first index is a map with a pointer to a c-string (the name of the named object)
5940   as a key and a structure with information of the dynamically allocated object
5941   (the most important being the address and the size of the object).
5942
5943*  The second index is used to implement "unique instances"
5944   and is basically the same as the first index,
5945   but the name of the object comes from a `typeid(T).name()` operation.
5946
5947The memory needed to store [name pointer, object information] pairs in the index is
5948allocated also via the *memory algorithm*, so we can tell that internal indexes
5949are just like ordinary user objects built in the segment. The rest of the memory
5950to store the name of the object, the object itself, and meta-data for
5951destruction/deallocation is allocated using the *memory algorithm* in a single
5952`allocate()` call.
5953
5954As seen, the [*segment manager] knows [*nothing] about shared memory/memory mapped files.
5955The [*segment manager] itself does not allocate portions of the segment,
5956it just asks the *memory algorithm* to allocate the needed memory from the rest
5957of the segment. The [*segment manager] is a class built above the memory algorithm
5958that offers named object construction, unique instance constructions, and many
5959other services.
5960
5961The [*segment manager] is implemented in [*Boost.Interprocess] by
5962the [classref boost::interprocess::segment_manager segment_manager] class.
5963
5964[c++]
5965
5966   template<class CharType
5967           ,class MemoryAlgorithm
5968           ,template<class IndexConfig> class IndexType>
5969   class segment_manager;
5970
5971As seen, the segment manager is quite generic: we can specify the character type
5972to be used to identify named objects, we can specify the memory algorithm that will
5973control dynamically the portions of the memory segment, and we can specify
5974also the index type that will store the [name pointer, object information] mapping.
5975We can construct our own index types as explained in
5976[link interprocess.customizing_interprocess.custom_indexes Building custom indexes] section.
5977
5978[endsect]
5979
5980[section:architecture_managed_memory Boost.Interprocess managed memory segments]
5981
5982The [*Boost.Interprocess] managed memory segments that construct the shared memory/memory
5983mapped file, place there the segment manager and forward the user requests to the
5984segment manager. For example, [classref boost::interprocess::basic_managed_shared_memory basic_managed_shared_memory]
5985is a [*Boost.Interprocess] managed memory segment that works with shared memory.
5986[classref boost::interprocess::basic_managed_mapped_file basic_managed_mapped_file] works with memory mapped files, etc...
5987
5988Basically, the interface of a [*Boost.Interprocess] managed memory segment is the same as
5989the [*segment manager] but it also offers functions to "open", "create", or "open or create"
5990shared memory/memory-mapped files segments and initialize all needed resources.
5991Managed memory segment classes are not built in shared memory or memory mapped files, they
5992are normal C++ classes that store a pointer to the segment manager (which is built
5993in shared memory or memory mapped files).
5994
5995Apart from this, managed memory segments offer specific functions: `managed_mapped_file`
5996offers functions to flush memory contents to the file, `managed_heap_memory` offers
5997functions to expand the memory, etc...
5998
5999Most of the functions of [*Boost.Interprocess] managed memory segments can be shared
6000between all managed memory segments, since many times they just forward the functions
6001to the segment manager. Because of this,
6002in [*Boost.Interprocess] all managed memory segments derive from a common class that
6003implements memory-independent (shared memory, memory mapped files) functions:
6004[@../../boost/interprocess/detail/managed_memory_impl.hpp
6005boost::interprocess::ipcdetail::basic_managed_memory_impl]
6006
6007Deriving from this class, [*Boost.Interprocess] implements several managed memory
6008classes, for different memory backends:
6009
6010* [classref boost::interprocess::basic_managed_shared_memory   basic_managed_shared_memory] (for shared memory).
6011* [classref boost::interprocess::basic_managed_mapped_file     basic_managed_mapped_file] (for memory mapped files).
6012* [classref boost::interprocess::basic_managed_heap_memory     basic_managed_heap_memory] (for heap allocated memory).
6013* [classref boost::interprocess::basic_managed_external_buffer basic_managed_external_buffer] (for user provided external buffer).
6014
6015[endsect]
6016
6017[endsect]
6018
6019[section:allocators_containers Allocators and containers]
6020
6021[section:allocators Boost.Interprocess allocators]
6022
6023The [*Boost.Interprocess] STL-like allocators are fairly simple and follow the usual C++
6024allocator approach. Normally, allocators for STL containers are based above new/delete
6025operators and above those, they implement pools, arenas and other allocation tricks.
6026
6027In [*Boost.Interprocess] allocators, the approach is similar, but all allocators are based
6028on the *segment manager*. The segment manager is the only one that provides from simple
6029memory allocation to named object creations. [*Boost.Interprocess] allocators always store
6030a pointer to the segment manager, so that they can obtain memory from the segment or share
6031a common pool between allocators.
6032
6033As you can imagine, the member pointers of the allocator are not a raw pointers, but
6034pointer types defined by the `segment_manager::void_pointer` type. Apart from this,
6035the `pointer` typedef of [*Boost.Interprocess] allocators is also of the same type of
6036`segment_manager::void_pointer`.
6037
6038This means that if our allocation algorithm defines `void_pointer` as `offset_ptr<void>`,
6039`boost::interprocess::allocator<T>` will store an `offset_ptr<segment_manager>`
6040to point to the segment manager and the `boost::interprocess::allocator<T>::pointer` type
6041will be `offset_ptr<T>`. This way, [*Boost.Interprocess] allocators can be placed in the
6042memory segment managed by the segment manager, that is, shared memory, memory mapped files,
6043etc...
6044
6045[endsect]
6046
6047[section:implementation_segregated_storage_pools Implementation of [*Boost.Interprocess] segregated storage pools]
6048
6049Segregated storage pools are simple and follow the classic segregated storage algorithm.
6050
6051*  The pool allocates chunks of memory using the segment manager's raw memory
6052   allocation functions.
6053*  The chunk contains a pointer to form a singly linked list of chunks. The pool
6054   will contain a pointer to the first chunk.
6055*  The rest of the memory of the chunk is divided in nodes of the requested size and
6056   no memory is used as payload for each node. Since the memory of a free node
6057   is not used that memory is used to place a pointer to form a singly linked list of
6058   free nodes. The pool has a pointer to the first free node.
6059*  Allocating a node is just taking the first free node from the list. If the list
6060   is empty, a new chunk is allocated, linked in the list of chunks and the new free
6061   nodes are linked in the free node list.
6062*  Deallocation returns the node to the free node list.
6063*  When the pool is destroyed, the list of chunks is traversed and memory is returned
6064   to the segment manager.
6065
6066The pool is implemented by the
6067[@../../boost/interprocess/allocators/detail/node_pool.hpp
6068private_node_pool and shared_node_pool] classes.
6069
6070[endsect]
6071
6072[section:implementation_adaptive_pools Implementation of [*Boost.Interprocess] adaptive pools]
6073
6074Adaptive pools are a variation of segregated lists but they have a more complicated
6075approach:
6076
6077*  Instead of using raw allocation, the pool allocates [*aligned] chunks of memory
6078   using the segment manager. This is an [*essential] feature since a node can reach
6079   its chunk information applying a simple mask to its address.
6080
6081*  The chunks contains pointers to form a doubly linked list of chunks and
6082   an additional pointer to create a singly linked list of free nodes placed
6083   on that chunk. So unlike the segregated storage algorithm, the free list
6084   of nodes is implemented [*per chunk].
6085
6086*  The pool maintains the chunks in increasing order of free nodes. This improves
6087   locality and minimizes the dispersion of node allocations across the chunks
6088   facilitating the creation of totally free chunks.
6089
6090*  The pool has a pointer to the chunk with the minimum (but not zero) free nodes.
6091   This chunk is called the "active" chunk.
6092
6093*  Allocating a node is just returning the first free node of the "active" chunk.
6094   The list of chunks is reordered according to the free nodes count.
6095   The pointer to the "active" pool is updated if necessary.
6096
6097*  If the pool runs out of nodes, a new chunk is allocated, and pushed back in the
6098   list of chunks. The pointer to the "active" pool is updated if necessary.
6099
6100*  Deallocation returns the node to the free node list of its chunk and updates
6101   the "active" pool accordingly.
6102
6103*  If the number of totally free chunks exceeds the limit, chunks are returned
6104   to the segment manager.
6105
6106*  When the pool is destroyed, the list of chunks is traversed and memory is returned
6107   to the segment manager.
6108
6109The adaptive pool is implemented by the
6110[@../../boost/interprocess/allocators/detail/adaptive_node_pool.hpp
6111private_adaptive_node_pool and adaptive_node_pool] classes.
6112
6113[endsect]
6114
6115[section:architecture_containers Boost.Interprocess containers]
6116
6117[*Boost.Interprocess] containers are standard conforming counterparts of STL containers
6118in `boost::interprocess` namespace, but with these little details:
6119
6120*  [*Boost.Interprocess] STL containers don't assume that memory allocated with
6121   an allocator can be deallocated with other allocator of
6122   the same type. They always compare allocators with `operator==()`
6123   to know if this is possible.
6124
6125*  The pointers of the internal structures of the [*Boost.Interprocess] containers are
6126   of the same type the `pointer` type defined by the allocator of the container. This
6127   allows placing containers in managed memory segments mapped in different base addresses.
6128
6129[endsect]
6130
6131[endsect]
6132
6133[section:performance Performance of Boost.Interprocess]
6134
6135This section tries to explain the performance characteristics of [*Boost.Interprocess],
6136so that you can optimize [*Boost.Interprocess] usage if you need more performance.
6137
6138[section:performance_allocations Performance of raw memory allocations]
6139
6140You can have two types of raw memory allocations with [*Boost.Interprocess] classes:
6141
6142*  [*Explicit]: The user calls `allocate()` and  `deallocate()` functions of
6143   managed_shared_memory/managed_mapped_file... managed memory segments. This call is
6144   translated to a `MemoryAlgorithm::allocate()` function, which means that you
6145   will need just the time that the memory algorithm associated with the managed memory segment
6146   needs to allocate data.
6147
6148*  [*Implicit]: For example, you are using `boost::interprocess::allocator<...>` with
6149   [*Boost.Interprocess] containers. This allocator calls the same `MemoryAlgorithm::allocate()`
6150   function than the explicit method, [*every] time a vector/string has to reallocate its
6151   buffer or [*every] time you insert an object in a node container.
6152
6153If you see that memory allocation is a bottleneck in your application, you have
6154these alternatives:
6155
6156*  If you use map/set associative containers, try using `flat_map` family instead
6157   of the map family if you mainly do searches and the insertion/removal is mainly done
6158   in an initialization phase. The overhead is now when the ordered vector has to
6159   reallocate its storage and move data. You can also call the `reserve()` method
6160   of these containers when you know beforehand how much data you will insert.
6161   However in these containers iterators are invalidated in insertions so this
6162   substitution is only effective in some applications.
6163
6164*  Use a [*Boost.Interprocess] pooled allocator for node containers, because pooled
6165   allocators call `allocate()` only when the pool runs out of nodes. This is pretty
6166   efficient (much more than the current default general-purpose algorithm) and this
6167   can save a lot of memory. See
6168   [link interprocess.allocators_containers.stl_allocators_segregated_storage Segregated storage node allocators] and
6169   [link interprocess.allocators_containers.stl_allocators_adaptive Adaptive node allocators] for more information.
6170
6171*  Write your own memory algorithm. If you have experience with memory allocation algorithms
6172   and you think another algorithm is better suited than the default one for your application,
6173   you can specify it in all [*Boost.Interprocess] managed memory segments. See the section
6174   [link interprocess.customizing_interprocess.custom_interprocess_alloc Writing a new shared memory allocation algorithm]
6175   to know how to do this. If you think its better than the default one for general-purpose
6176   applications, be polite and donate it to [*Boost.Interprocess] to make it default!
6177
6178[endsect]
6179
6180[section:performance_named_allocation Performance of named allocations]
6181
6182[*Boost.Interprocess] allows the same parallelism as two threads writing to a common
6183structure, except when the user creates/searches named/unique objects. The steps
6184when creating a named object are these:
6185
6186*  Lock a recursive mutex (so that you can make named allocations inside
6187   the constructor of the object to be created).
6188
6189*  Try to insert the [name pointer, object information] in the name/object index.
6190   This lookup has to assure that the name has not been used before.
6191   This is achieved calling `insert()` function in the index. So the time this
6192   requires is dependent on the index type (ordered vector, tree, hash...).
6193   This can require a call to the memory algorithm allocation function if
6194   the index has to be reallocated, it's a node allocator, uses pooled allocations...
6195
6196*  Allocate a single buffer to hold the name of the object, the object itself,
6197   and meta-data for destruction (number of objects, etc...).
6198
6199*  Call the constructors of the object being created. If it's an array, one
6200   constructor per array element.
6201
6202*  Unlock the recursive mutex.
6203
6204The steps when destroying a named object using the name of the object
6205(`destroy<T>(name)`) are these:
6206
6207*  Lock a recursive mutex .
6208
6209*  Search in the index the entry associated to that name. Copy that information and
6210   erase the index entry. This is done using `find(const key_type &)` and `erase(iterator)`
6211   members of the index. This can require element reordering if the index is a
6212   balanced tree, an ordered vector...
6213
6214*  Call the destructor of the object (many if it's an array).
6215
6216*  Deallocate the memory buffer containing the name, metadata and the object itself
6217   using the allocation algorithm.
6218
6219*  Unlock the recursive mutex.
6220
6221The steps when destroying a named object using the pointer of the object
6222(`destroy_ptr(T *ptr)`) are these:
6223
6224*  Lock a recursive mutex .
6225
6226*  Depending on the index type, this can be different:
6227
6228   *  If the index is a node index, (marked with `boost::interprocess::is_node_index`
6229      specialization): Take the iterator stored near the object and call
6230      `erase(iterator)`. This can require element reordering if the index is a
6231      balanced tree, an ordered vector...
6232
6233   *  If it's not an node index: Take the name stored near the object and erase
6234      the index entry calling `erase(const key &). This can require element reordering
6235      if the index is a balanced tree, an ordered vector...
6236
6237*  Call the destructor of the object (many if it's an array).
6238
6239*  Deallocate the memory buffer containing the name, metadata and the object itself
6240   using the allocation algorithm.
6241
6242*  Unlock the recursive mutex.
6243
6244If you see that the performance is not good enough you have these alternatives:
6245
6246*  Maybe the problem is that the lock time is too big and it hurts parallelism.
6247   Try to reduce the number of named objects in the global index and if your
6248   application serves several clients try to build a new managed memory segment
6249   for each one instead of using a common one.
6250
6251*  Use another [*Boost.Interprocess] index type if you feel the default one is
6252   not fast enough. If you are not still satisfied, write your own index type. See
6253   [link interprocess.customizing_interprocess.custom_indexes Building custom indexes] for this.
6254
6255*  Destruction via pointer is at least as fast as using the name of the object and
6256   can be faster (in node containers, for example). So if your problem is that you
6257   make at lot of named destructions, try to use the pointer. If the index is a
6258   node index you can save some time.
6259
6260[endsect]
6261
6262[endsect]
6263
6264[endsect]
6265
6266[section:customizing_interprocess Customizing Boost.Interprocess]
6267
6268[section:custom_interprocess_alloc Writing a new shared memory allocation algorithm]
6269
6270If the default algorithm does not satisfy user requirements,
6271it's easy to provide different algorithms like bitmapping or
6272more advanced segregated lists to meet requirements. The class implementing
6273the algorithm must be compatible with shared memory, so it shouldn't have any
6274virtual function or virtual inheritance or
6275any indirect base class with virtual function or inheritance.
6276
6277This is the interface to be implemented:
6278
6279[c++]
6280
6281   class my_algorithm
6282   {
6283      public:
6284
6285      //!The mutex type to be used by the rest of Interprocess framework
6286      typedef implementation_defined   mutex_family;
6287
6288      //!The pointer type to be used by the rest of Interprocess framework
6289      typedef implementation_defined   void_pointer;
6290
6291      //!Constructor. "size" is the total size of the managed memory segment,
6292      //!"extra_hdr_bytes" indicates the extra bytes after the sizeof(my_algorithm)
6293      //!that the allocator should not use at all.
6294      my_algorithm (std::size_t size, std::size_t extra_hdr_bytes);
6295
6296      //!Obtains the minimum size needed by the algorithm
6297      static std::size_t get_min_size (std::size_t extra_hdr_bytes);
6298
6299      //!Allocates bytes, returns 0 if there is not more memory
6300      void* allocate (std::size_t nbytes);
6301
6302      //!Deallocates previously allocated bytes
6303      void  deallocate (void *adr);
6304
6305      //!Returns the size of the memory segment
6306      std::size_t get_size()  const;
6307
6308      //!Increases managed memory in extra_size bytes more
6309      void grow(std::size_t extra_size);
6310      /*...*/
6311   };
6312
6313Let's see the public typedefs to define:
6314
6315[c++]
6316
6317   typedef /* . . . */ void_pointer;
6318   typedef /* . . . */ mutex_family;
6319
6320The `void_pointer` typedef specifies the pointer type to be used in
6321the [*Boost.Interprocess] framework that uses the algorithm. For example, if we define
6322
6323[c++]
6324
6325   typedef void * void_pointer;
6326
6327all [*Boost.Interprocess] framework using this algorithm will use raw pointers as members.
6328But if we define:
6329
6330[c++]
6331
6332   typedef offset_ptr<void> void_pointer;
6333
6334then all [*Boost.Interprocess] framework will use relative pointers.
6335
6336The `mutex_family` is a structure containing typedefs
6337for different interprocess_mutex types to be used in the [*Boost.Interprocess]
6338framework. For example the defined
6339
6340[c++]
6341
6342   struct mutex_family
6343   {
6344      typedef boost::interprocess::interprocess_mutex             mutex_type;
6345      typedef boost::interprocess::interprocess_recursive_mutex   recursive_mutex_type;
6346   };
6347
6348defines all interprocess_mutex types using boost::interprocess interprocess_mutex types.
6349The user can specify the desired mutex family.
6350
6351[c++]
6352
6353   typedef mutex_family mutex_family;
6354
6355The new algorithm (let's call it *my_algorithm*) must implement all the functions
6356that boost::interprocess::rbtree_best_fit class offers:
6357
6358*  [*my_algorithm]'s constructor must take 2 arguments:
6359   *  [*size] indicates the total size of the managed memory segment, and
6360      [*my_algorithm] object will be always constructed a at offset 0
6361      of the memory segment.
6362
6363   *  The [*extra_hdr_bytes] parameter indicates the number of bytes after
6364      the offset `sizeof(my_algorithm)` that [*my_algorithm] can't use at all. This extra
6365      bytes will be used to store additional data that should not be overwritten.
6366      So, [*my_algorithm] will be placed at address XXX of the memory segment, and will
6367      manage the [*[XXX + sizeof(my_algorithm) + extra_hdr_bytes, XXX + size)] range of
6368      the segment.
6369
6370*  The [*get_min_size()] function should return the minimum space the algorithm
6371   needs to be valid with the passed [*extra_hdr_bytes] parameter. This function will
6372   be used to check if the memory segment is big enough to place the algorithm there.
6373
6374*  The [*allocate()] function must return 0 if there is no more available memory.
6375   The memory returned by [*my_algorithm]
6376   must be aligned to the most restrictive memory alignment of the system.
6377   This function should be executed with the synchronization capabilities offered
6378   by `typename mutex_family::mutex_type` interprocess_mutex. That means, that if we define
6379   `typedef mutex_family mutex_family;` then this function should offer
6380   the same synchronization as if it was surrounded by an interprocess_mutex lock/unlock.
6381   Normally, this is implemented using a member of type `mutex_family::mutex_type`, but
6382   it could be done using atomic instructions or lock free algorithms.
6383
6384*  The [*deallocate()] function must make the returned buffer available for new
6385   allocations. This function should offer the same synchronization as `allocate()`.
6386
6387*  The [*size()] function will return the passed [*size] parameter in the constructor.
6388   So, [*my_algorithm] should store the size internally.
6389
6390*  The [*grow()] function will expand the managed memory by [*my_algorithm] in [*extra_size]
6391   bytes. So [*size()] function should return the updated size,
6392   and the new managed memory range will be (if the address where the algorithm is
6393   constructed is XXX): [*[XXX + sizeof(my_algorithm) + extra_hdr_bytes, XXX + old_size + extra_size)].
6394   This function should offer the same synchronization as `allocate()`.
6395
6396That's it. Now we can create new managed shared memory that uses our new algorithm:
6397
6398[c++]
6399
6400   //Managed memory segment to allocate named (c-string) objects
6401   //using a user-defined memory allocation algorithm
6402   basic_managed_shared_memory<char,
6403                            ,my_algorithm
6404                            ,flat_map_index>
6405      my_managed_shared_memory;
6406
6407[endsect]
6408
6409[section:custom_allocators Building custom STL compatible allocators for Boost.Interprocess]
6410
6411If provided STL-like allocators don't satisfy user needs, the user
6412can implement another STL compatible allocator using raw memory allocation
6413and named object construction functions.
6414The user can this way implement more suitable allocation
6415schemes on top of basic shared memory allocation schemes,
6416just like more complex allocators are built on top of
6417new/delete functions.
6418
6419When using a managed memory segment, [*get_segment_manager()]
6420function returns a pointer to the segment manager. With this pointer,
6421the raw memory allocation and named object construction functions can be
6422called directly:
6423
6424[c++]
6425
6426   //Create the managed shared memory and initialize resources
6427   managed_shared_memory segment
6428      (create_only
6429      ,"/MySharedMemory"   //segment name
6430      ,65536);             //segment size in bytes
6431
6432   //Obtain the segment manager
6433   managed_shared_memory::segment_manager *segment_mngr
6434      = segment.get_segment_manager();
6435
6436   //With the segment manager, now we have access to all allocation functions
6437   segment_mngr->deallocate(segment_mngr->allocate(32));
6438   segment_mngr->construct<int>("My_Int")[32](0);
6439   segment_mngr->destroy<int>("My_Int");
6440
6441   //Initialize the custom, managed memory segment compatible
6442   //allocator with the segment manager.
6443   //
6444   //MySTLAllocator uses segment_mngr->xxx functions to
6445   //implement its allocation scheme
6446   MySTLAllocator<int> stl_alloc(segment_mngr);
6447
6448   //Alias a new vector type that uses the custom STL compatible allocator
6449   typedef std::vector<int, MySTLAllocator<int> > MyVect;
6450
6451   //Construct the vector in shared memory with the allocator as constructor parameter
6452   segment.construct<MyVect>("MyVect_instance")(stl_alloc);
6453
6454The user can create new STL compatible allocators that use the segment manager to access
6455to all memory management/object construction functions. All [*Boost.Interprocess]' STL
6456compatible allocators are based on this approach. [*Remember] that to be compatible with
6457managed memory segments, allocators should define their *pointer* typedef as the same
6458pointer family as `segment_manager::void_pointer` typedef. This means that if `segment_manager::void_pointer` is
6459`offset_ptr<void>`, `MySTLAllocator<int>` should define `pointer` as `offset_ptr<int>`. The
6460reason for this is that allocators are members of containers, and if we want to put
6461the container in a managed memory segment, the allocator should be ready for that.
6462
6463[endsect]
6464
6465[section:custom_indexes Building custom indexes]
6466
6467The managed memory segment uses a name/object index to
6468speed up object searching and creation. Default specializations of
6469managed memory segments (`managed_shared_memory` for example),
6470use `boost::interprocess::flat_map` as index.
6471
6472However, the index type can be chosen via template parameter, so that
6473the user can define its own index type if he needs that. To construct
6474a new index type, the user must create a class with the following guidelines:
6475
6476* The interface of the index must follow the common public interface of std::map
6477  and std::tr1::unordered_map including public typedefs.
6478  The `value_type` typedef can be of type:
6479
6480[c++]
6481
6482   std::pair<key_type, mapped_type>
6483
6484or
6485
6486[c++]
6487
6488   std::pair<const key_type, mapped_type>
6489
6490
6491so that ordered arrays or deques can be used as index types.
6492Some known classes following this basic interface are `boost::unordered_map`,
6493`boost::interprocess::flat_map` and `boost::interprocess::map`.
6494
6495* The class must be a class template taking only a traits struct of this type:
6496
6497[c++]
6498
6499   struct index_traits
6500   {
6501      typedef /*...*/   key_type;
6502      typedef /*...*/   mapped_type;
6503      typedef /*...*/   segment_manager;
6504   };
6505
6506[c++]
6507
6508   template <class IndexTraits>
6509   class my_index_type;
6510
6511The `key_type` typedef of the passed `index_traits` will be a specialization of the
6512following class:
6513
6514[c++]
6515
6516   //!The key of the named allocation information index. Stores a to
6517   //!a null string and the length of the string to speed up sorting
6518   template<...>
6519   struct index_key
6520   {
6521      typedef /*...*/                              char_type;
6522      typedef /*...*/                              const_char_ptr_t;
6523
6524      //Pointer to the object's name (null terminated)
6525      const_char_ptr_t                             mp_str;
6526
6527      //Length of the name buffer (null NOT included)
6528      std::size_t                                  m_len;
6529
6530      //!Constructor of the key
6531      index_key (const CharT *name, std::size_t length);
6532
6533      //!Less than function for index ordering
6534      bool operator < (const index_key & right) const;
6535
6536      //!Equal to function for index ordering
6537      bool operator == (const index_key & right) const;
6538   };
6539
6540The `mapped_type` is not directly modified by the customized index but it is needed to
6541define the index type. The *segment_manager* will be the type of the segment manager that
6542will manage the index. `segment_manager` will define interesting internal types like
6543`void_pointer` or `mutex_family`.
6544
6545* The constructor of the customized index type must take a pointer to segment_manager
6546  as constructor argument:
6547
6548[c++]
6549
6550   constructor(segment_manager *segment_mngr);
6551
6552* The index must provide a memory reservation function, that optimizes the index if the
6553  user knows the number of elements to be inserted in the index:
6554
6555[c++]
6556
6557   void reserve(std::size_t n);
6558
6559For example, the index type `flat_map_index` based in `boost::interprocess::flat_map`
6560is just defined as:
6561
6562[import ../../../boost/interprocess/indexes/flat_map_index.hpp]
6563[flat_map_index]
6564
6565
6566If the user is defining a node container based index (a container whose iterators
6567are not invalidated when inserting or erasing other elements), [*Boost.Interprocess] can
6568optimize named object destruction when destructing via pointer. [*Boost.Interprocess] can
6569store an iterator next to the object and instead of using the name of the object to erase
6570the index entry, it uses the iterator, which is a faster operation. So if you are creating
6571a new node container based index (for example, a tree), you should define an
6572specialization of `boost::interprocess::is_node_index<...>` defined in
6573`<boost/interprocess/detail/utilities.hpp>`:
6574
6575[c++]
6576
6577   //!Trait classes to detect if an index is a node
6578   //!index. This allows more efficient operations
6579   //!when deallocating named objects.
6580   template<class MapConfig>
6581   struct is_node_index
6582      <my_index<MapConfig> >
6583   {
6584      static const bool value = true;
6585   };
6586
6587Interprocess also defines other index types:
6588
6589* [*boost::map_index] uses *boost::interprocess::map* as index type.
6590
6591* [*boost::null_index] that uses an dummy index type if the user just needs
6592  anonymous allocations and wants to save some space and class instantiations.
6593
6594Defining a new managed memory segment that uses the new index is easy. For
6595example, a new managed shared memory that uses the new index:
6596
6597[c++]
6598
6599   //!Defines a managed shared memory with a c-strings as
6600   //!a keys, the red-black tree best fit algorithm (with process-shared mutexes
6601   //!and offset_ptr pointers) as raw shared memory management algorithm
6602   //!and a custom index
6603   typedef
6604      basic_managed_shared_memory <
6605                                 char,
6606                                 rbtree_best_fit<mutex_family>,
6607                                 my_index_type
6608                                >
6609      my_managed_shared_memory;
6610
6611[endsect]
6612
6613[endsect]
6614
6615
6616[section:acknowledgements_notes Acknowledgements, notes and links]
6617
6618[section:notes_windows Notes for Windows users]
6619
6620[section:notes_windows_com_init COM Initialization]
6621
6622[*Boost.Interprocess] uses the Windows COM library to implement some features and initializes
6623it with concurrency model `COINIT_APARTMENTTHREADED`.
6624If the COM library was already initialized by the calling thread for another concurrency model, [*Boost.Interprocess]
6625handles this gracefully and uses COM calls for the already initialized model. If for some reason, you
6626want [*Boost.Interprocess] to initialize the COM library with another model, define the macro
6627`BOOST_INTERPROCESS_WINDOWS_COINIT_MODEL` before including [*Boost.Interprocess] to one of these values:
6628
6629* `COINIT_APARTMENTTHREADED_BIPC`
6630* `COINIT_MULTITHREADED_BIPC`
6631* `COINIT_DISABLE_OLE1DDE_BIPC`
6632* `COINIT_SPEED_OVER_MEMORY_BIPC`
6633
6634[endsect]
6635
6636[section:notes_windows_shm_folder Shared memory emulation folder]
6637
6638Shared memory (`shared_memory_object`) is implemented in Windows using memory mapped files, placed in a
6639shared directory in the shared documents folder (`SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Common AppData`).
6640This directory name is the last bootup time obtained via COM calls (if `BOOST_INTERPROCESS_BOOTSTAMP_IS_LASTBOOTUPTIME`) defined
6641or searching the system log for a startup event (the default implementation), so that each bootup shared memory is created in a new
6642folder obtaining kernel persistence shared memory.
6643
6644If using `BOOST_INTERPROCESS_BOOTSTAMP_IS_LASTBOOTUPTIME`, due to COM implementation related errors,
6645in Boost 1.48 & Boost 1.49 the bootup-time folder was dumped and files
6646were directly created in shared documents folder, reverting to filesystem persistence shared memory. Boost 1.50 fixed those issues
6647and recovered bootup time directory and kernel persistence. If you need to reproduce Boost 1.48 & Boost 1.49 behaviour to communicate
6648with applications compiled with that version, comment `#define BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME` directive
6649in the Windows configuration part of `boost/interprocess/detail/workaround.hpp`.
6650
6651If using the default implementation, (`BOOST_INTERPROCESS_BOOTSTAMP_IS_LASTBOOTUPTIME` undefined) and the Startup Event is not
6652found, this might be due to some buggy software that floods or erases the event log.
6653
6654In any error case (shared documents folder is not defined or bootup time could not be obtained, the library throws an error. You still
6655can use [*Boost.Interprocess] defining your own directory as the shared directory. When your shared directory is a compile-time constant,
6656define `BOOST_INTERPROCESS_SHARED_DIR_PATH` when using the library and that path will be used to place shared memory files. When you have
6657to determine the shared directory at runtime, define `BOOST_INTERPROCESS_SHARED_DIR_FUNC` and implement the function
6658
6659[c++]
6660
6661   namespace boost {
6662       namespace interprocess {
6663           namespace ipcdetail {
6664               void get_shared_dir(std::string &shared_dir);
6665           }
6666       }
6667   }
6668
6669[endsect]
6670
6671[section:boost_use_windows_h BOOST_USE_WINDOWS_H support]
6672
6673If `BOOST_USE_WINDOWS_H` is defined, <windows.h> and other windows SDK files are included,
6674otherwise the library declares needed functions and structures to reduce the impact of including
6675those heavy headers.
6676
6677[endsect]
6678
6679[endsect]
6680
6681[section:notes_linux Notes for Linux users]
6682
6683[section:notes_linux_shm_folder Shared memory emulation folder]
6684
6685On systems without POSIX shared memory support, shared memory objects are implemented as memory mapped files, using a directory
6686placed in "/tmp" that can include (if `BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME` is defined) the last bootup time (if the OS supports it).
6687As in Windows, in any error case obtaining this directory the library throws an error . When your shared directory is a compile-time constant,
6688define `BOOST_INTERPROCESS_SHARED_DIR_PATH` when using the library and that path will be used to place shared memory files. When you have
6689to determine the shared directory at runtime, define `BOOST_INTERPROCESS_SHARED_DIR_FUNC` and implement the function
6690
6691[c++]
6692
6693   namespace boost {
6694       namespace interprocess {
6695           namespace ipcdetail {
6696               void get_shared_dir(std::string &shared_dir);
6697           }
6698       }
6699   }
6700
6701
6702[endsect]
6703
6704[section:notes_linux_overcommit Overcommit]
6705
6706The committed address space is the total amount of virtual memory (swap or physical memory/RAM) that the kernel might have to supply
6707if all applications decide to access all of the memory they've requested from the kernel.
6708By default, Linux allows processes to commit more virtual memory than available in the system. If that memory is not
6709accessed, no physical memory + swap is actually used.
6710
6711The reason for this behaviour is that Linux tries to optimize memory usage on forked processes; fork() creates a full copy of
6712the process space, but with overcommitted memory, in this new forked instance only pages which have been written to actually need
6713to be allocated by the kernel. If applications access more memory than available, then the kernel must free memory in the hard way:
6714the OOM (Out Of Memory)-killer picks some processes to kill in order to recover memory.
6715
6716[*Boost.Interprocess] has no way to change this behaviour and users might suffer the OOM-killer when accessing shared memory.
6717According to the [@http://www.kernel.org/doc/Documentation/vm/overcommit-accounting Kernel documentation], the
6718Linux kernel supports several overcommit modes. If you need non-kill guarantees in your application, you should
6719change this overcommit behaviour.
6720
6721[endsect]
6722
6723[endsect]
6724
6725[section:notes_freebsd Notes for FreeBSD users]
6726
6727[section:notes_freebsd_umtx_vnode_persistent Process-shared synchronization primitives and ['kern.ipc.umtx_vnode_persistent]]
6728
6729Starting from FreeBSD 11, declares the macro _POSIX_THREAD_PROCESS_SHARED. However, the default behavior is different from the one on Linux.
6730If you want to use this feature, according to the man page of libthr(3), you should check sysctl's ['kern.ipc.umtx_vnode_persistent]:
6731
6732* ['kern.ipc.umtx_vnode_persistent]: By default, a shared lock backed by a mapped file in memory is automatically destroyed on the last
6733   unmap of the corresponding file's page, which is allowed by POSIX. Setting the sysctl to 1 makes such a shared lock object persist until
6734   the vnode is recycled by the Virtual File System. Note that in case file is not opened and not mapped, the kernel might recycle it at
6735   any moment, making this sysctl less useful than it sounds.
6736
6737If you want mapped files to remain useful after the last handle is closed, set this variable to 1.
6738
6739[endsect]
6740
6741[endsect]
6742
6743[section:thanks_to Thanks to...]
6744
6745Many people have contributed with ideas and revisions, so this is the place to
6746thank them:
6747
6748*  Thanks to all people who have shown interest in the library and have downloaded
6749   and tested the snapshots.
6750
6751*  Thanks to [*Francis Andre] and [*Anders Hybertz] for their ideas and suggestions.
6752   Many of them are not implemented yet but I hope to include them when library gets some stability.
6753
6754*  Thanks to [*Matt Doyle], [*Steve LoBasso], [*Glenn Schrader], [*Hiang Swee Chiang],
6755   [*Phil Endecott], [*Rene Rivera],
6756   [*Harold Pirtle], [*Paul Ryan],
6757   [*Shumin Wu], [*Michal Wozniak], [*Peter Johnson],
6758   [*Alex Ott], [*Shane Guillory], [*Steven Wooding]
6759   and [*Kim Barrett] for their bug fixes and library testing.
6760
6761*  Thanks to [*Martin Adrian] who suggested the use of Interprocess framework for user defined buffers.
6762
6763*  Thanks to [*Synge Todo] for his boostbook-doxygen patch to improve Interprocess documentation.
6764
6765*  Thanks to [*Olaf Krzikalla] for his Intrusive library. I have taken some ideas to
6766   improve red black tree implementation from his library.
6767
6768*  Thanks to [*Daniel James] for his unordered_map/set family and his help with allocators.
6769   His great unordered implementation has been a reference to design exception safe containers.
6770
6771*  Thanks to [*Howard Hinnant] for his amazing help, specially explaining allocator swapping,
6772   move semantics and for developing upgradable mutex and lock transfer features.
6773
6774*  Thanks to [*Pavel Vozenilek] for his continuous review process, suggestions, code and
6775   help. He is the major supporter of Interprocess library. The library has grown with his
6776   many and great advices.
6777
6778*  And finally, thank you to all Boosters. [*Long live to C++!]
6779
6780[endsect]
6781
6782[section:release_notes Release Notes]
6783
6784[section:release_notes_boost_1_74_00 Boost 1.74 Release]
6785
6786* [*ABI breaking]: Option `BOOST_INTERPROCESS_BOOTSTAMP_IS_SESSION_MANAGER_BASED` is now the default value.
6787  You can obtain the pre-Boost 1.73 behaviour defining `BOOST_INTERPROCESS_BOOTSTAMP_IS_EVENTLOG_BASED`.
6788  The old and broken pre-Boost 1.54 behaviour (`BOOST_INTERPROCESS_BOOTSTAMP_IS_LASTBOOTUPTIME`) is no
6789  longer available.
6790
6791*  Fixed bugs:
6792   * [@https://github.com/boostorg/interprocess/issues/89 GitHub #89 (['"priv_size_from_mapping_size() calculates wrong value"])].
6793   * [@https://github.com/boostorg/interprocess/issues/99 GitHub #99 (['"Error in win32_api.hpp"])].
6794   * [@https://github.com/boostorg/interprocess/issues/105 GitHub #105 (['"Build failure with clang on Windows"])].
6795   * [@https://github.com/boostorg/interprocess/pull/119 GitHub #119 (['"Fix mingw compile error"])].
6796
6797[endsect]
6798
6799[section:release_notes_boost_1_71_00 Boost 1.71 Release]
6800
6801*  Fixed bugs:
6802   * [@https://github.com/boostorg/interprocess/pull/85 GitHub #85 (['"warning: Implicit conversion loses integer precision"])].
6803   * [@https://github.com/boostorg/interprocess/pull/86 GitHub #86 (['"warning: Possible misuse of comma operator"])].
6804
6805[endsect]
6806
6807[section:release_notes_boost_1_70_00 Boost 1.70 Release]
6808
6809*  Fixed bugs:
6810   * [@https://github.com/boostorg/interprocess/pull/51 GitHub Pull #51 (['"United handling of wait_for_single_object"])].
6811   * [@https://github.com/boostorg/interprocess/pull/78 GitHub Pull #78 (['"Fix -Wextra-semi clang warnings"])].
6812
6813[endsect]
6814
6815[section:release_notes_boost_1_69_00 Boost 1.69 Release]
6816
6817* Deprecated GCC < 4.3 and MSVC < 9.0 (Visual 2008) compilers.
6818
6819*  Fixed bugs:
6820   * [@https://github.com/boostorg/interprocess/issues/59 GitHub Issue #59 (['"warning: ISO C++ prohibits anonymous structs [-Wpedantic]"])].
6821   * [@https://github.com/boostorg/interprocess/issues/60 GitHub Issue #60 (['"warning: cast between incompatible function types from boost::interprocess::winapi::farproc_t..."])].
6822   * [@https://github.com/boostorg/interprocess/issues/61 GitHub Issue #61 (['"warning: struct winapi::*_BIPC has virtual functions and accessible non-virtual destructor"])].
6823   * [@https://github.com/boostorg/interprocess/issues/64 GitHub Issue #64 (['"UBSan: runtime error: load of value 4294967295, (...) for type 'boost::interprocess::mode_t'"])].
6824   * [@https://github.com/boostorg/interprocess/pull/68   GitHub Pull #68 (['"Prepare for C++20 and remove "throw()" usage"])].
6825   * [@https://github.com/boostorg/interprocess/pull/70   GitHub Pull #70 (['"Fix deadlock in named_condition::notify_one"])].
6826
6827[endsect]
6828
6829[section:release_notes_boost_1_68_00 Boost 1.68 Release]
6830*  Fixed bugs:
6831   * [@https://github.com/boostorg/interprocess/issues/53 GitHub Issue #53 (['"Crash waiting on condition variable from multiple processes in do_wait()"])].
6832   * [@https://github.com/boostorg/interprocess/issues/54 GitHub Issue #54 (['"fill_system_message() ignores an error returned by winapi::format_message()"])].
6833
6834[endsect]
6835
6836[section:release_notes_boost_1_67_00 Boost 1.67 Release]
6837*  Fixed bugs:
6838   * [@https://github.com/boostorg/interprocess/pull/45 GitHub Pull #45 (['"Make intrusive_ptr move constructible/assignable"])].
6839   * [@https://github.com/boostorg/interprocess/pull/48 GitHub Pull #48 (['"Win32: Fix read of reg_expand_sz type"])].
6840
6841[endsect]
6842
6843[section:release_notes_boost_1_66_00 Boost 1.66 Release]
6844*  Fixed bugs:
6845   * [@https://github.com/boostorg/interprocess/pull/41 GitHub Pull #41 (['"Data race in boost::interprocess::rbtree_best_fit"])].
6846
6847[endsect]
6848
6849[section:release_notes_boost_1_65_00 Boost 1.65 Release]
6850*  Fixed bugs:
6851   * [@https://github.com/boostorg/interprocess/pull/37 GitHub Pull #37 (['"Conditionally replace deprecated/removed std::auto_ptr..."])].
6852
6853[endsect]
6854
6855[section:release_notes_boost_1_64_00 Boost 1.64 Release]
6856*  Fixed bugs:
6857   * [@https://svn.boost.org/trac/boost/ticket/12617 Trac #12617 (['"clock_gettime not available on OS X 10.11"])].
6858   * [@https://svn.boost.org/trac/boost/ticket/12744 Trac #12744 (['"winapi::set_timer_resolution inadvertently changes timer resolution (Windows)"])].
6859   * [@https://github.com/boostorg/interprocess/pull/32 GitHub Pull #32 (['"Conform to std::pointer_traits requirements"])].
6860   * [@https://github.com/boostorg/interprocess/pull/33 GitHub Pull #33 (['"explicit cast to derived class" and "64/32 bit processes sharing"])].
6861   * [@https://github.com/boostorg/interprocess/pull/34 GitHub Pull #34 (['"Update example to use multi_index::member instead of BOOST_MULTI_INDEX_MEMBER"])].
6862   * [@https://github.com/boostorg/interprocess/pull/35 GitHub Pull #35 (['"Fixed options for cross-compilation"])].
6863
6864* New experimental option `BOOST_INTERPROCESS_BOOTSTAMP_IS_SESSION_MANAGER_BASED` from Windows systems.
6865  This option derives the unique bootstamp used to name the folder where shared memory is placed from registry values associated
6866  with the session manager. This option only works on Vista and later systems and might be more stable than the default version.
6867
6868[endsect]
6869
6870[section:release_notes_boost_1_63_00 Boost 1.63 Release]
6871*  Fixed bugs:
6872   * [@https://svn.boost.org/trac/boost/ticket/12499 Trac #12499 (['"Memory allocation fails"])].
6873   * [@https://github.com/boostorg/interprocess/pull/30 GitHub Pull #30 (['"Provide extension point so library user can provide default temp folder"])].
6874   * [@https://github.com/boostorg/interprocess/pull/31 GitHub Pull #31 (['"Add xsi_key(key_t) constructor"])].
6875
6876[endsect]
6877
6878[section:release_notes_boost_1_62_00 Boost 1.62 Release]
6879*  Fixed bugs:
6880   * [@https://github.com/boostorg/interprocess/pull/27 GitHub Pull #27 (['"Fix undefined behavior"])].
6881
6882[endsect]
6883
6884[section:release_notes_boost_1_61_00 Boost 1.61 Release]
6885*  Fixed bugs:
6886   * [@https://github.com/boostorg/interprocess/pull/23 GitHub Pull #23 (['"Fixed case sensitive for linux mingw"])].
6887
6888[endsect]
6889
6890[section:release_notes_boost_1_60_00 Boost 1.60 Release]
6891*  Improved [classref boost::interprocess::offset_ptr offset_ptr] performance and removed any undefined behaviour. No
6892   special cases needed for different compilers.
6893*  Fixed bugs:
6894   * [@https://svn.boost.org/trac/boost/ticket/11699 Trac #11699 (['"Forward declarations of std templates causes stack corruption under Visual Studio 2015"])].
6895
6896[endsect]
6897
6898[section:release_notes_boost_1_59_00 Boost 1.59 Release]
6899*  Fixed bugs:
6900   * [@https://svn.boost.org/trac/boost/ticket/5139 Trac #5139 (['"Initial Stream Position in Boost.Interprocess.Vectorstream"])].
6901   * [@https://github.com/boostorg/interprocess/pull/19 GitHub Pull #19 (['"Fix exception visibility"])]. Thanks to Romain-Geissler.
6902
6903[endsect]
6904
6905[section:release_notes_boost_1_58_00 Boost 1.58 Release]
6906*  Reduced some compile-time dependencies. Updated to Boost.Container changes.
6907*  Fixed bugs:
6908   * [@https://github.com/boostorg/interprocess/pull/13 GitHub Pull #13 (['"haiku: we don't have XSI shared memory, so don't try to use it"])].
6909     Thanks to Jessica Hamilton.
6910
6911[endsect]
6912
6913[section:release_notes_boost_1_57_00 Boost 1.57 Release]
6914*  Removed `unique_ptr`, now forwards boost::interprocess::unique_ptr to the general purpose
6915   `boost::movelib::unique_ptr` class from [*Boost.Move]. This implementation is closer to the standard
6916   `std::unique_ptr` implementation and it's better maintained.
6917*  Fixed bugs:
6918   * [@https://svn.boost.org/trac/boost/ticket/10262 Trac #10262 (['"AIX 6.1 bug with variable definition hz"])].
6919   * [@https://svn.boost.org/trac/boost/ticket/10229 Trac #10229 (['"Compiling errors in interprocess\detail\os_file_functions.hpp"])].
6920   * [@https://svn.boost.org/trac/boost/ticket/10506 Trac #10506 (['"Infinite loop in create_or_open_file"])].
6921   * [@https://github.com/boostorg/interprocess/pull/11 GitHub Pull #11 (['"Compile fix for BOOST_USE_WINDOWS_H"])].
6922
6923*  Reorganized Doxygen marks to obtain a better header reference.
6924
6925[endsect]
6926
6927[section:release_notes_boost_1_56_00 Boost 1.56 Release]
6928*  Fixed bugs:
6929   * [@https://svn.boost.org/trac/boost/ticket/9221 Trac #9221 (['"message_queue deadlock on linux"])].
6930   * [@https://svn.boost.org/trac/boost/ticket/9226 Trac #9226 (['"On some computers, Common Appdata is empty in registry, so boost interprocess cannot work"])].
6931   * [@https://svn.boost.org/trac/boost/ticket/9262 Trac #9262 (['"windows_intermodule_singleton breaks when calling a Debug dll from a Release executable"])].
6932   * [@https://svn.boost.org/trac/boost/ticket/9284 Trac #9284 (['"WaitForSingleObject(mutex) must handle WAIT_ABANDONED"])].
6933   * [@https://svn.boost.org/trac/boost/ticket/9285 Trac #9285 (['"CreateMutex returns NULL if fails"])].
6934   * [@https://svn.boost.org/trac/boost/ticket/9288 Trac #9288 (['"timed_wait does not check if it has expired"])].
6935   * [@https://svn.boost.org/trac/boost/ticket/9408 Trac #9408 (['"Android does not support XSI_SHARED_MEMORY_OBJECTS"]]).
6936   * [@https://svn.boost.org/trac/boost/ticket/9729 Trac #9729 (['"crash on managed_external_buffer object construction"]]).
6937   * [@https://svn.boost.org/trac/boost/ticket/9767 Trac #9767 (['"bootstamp generation causes error in case of corrupt Windows Event Log"])].
6938   * [@https://svn.boost.org/trac/boost/ticket/9835 Trac #9835 (['"Boost Interprocess fails to compile with Android NDK GCC 4.8, -Werror=unused-variable"])].
6939   * [@https://svn.boost.org/trac/boost/ticket/9911 Trac #9911 (['"get_tmp_base_dir(...) failure"])].
6940   * [@https://svn.boost.org/trac/boost/ticket/9946 Trac #9946 (['"ret_ptr uninitialized in init_atomic_func, fini_atomic_func"])].
6941   * [@https://svn.boost.org/trac/boost/ticket/10011 Trac #10011 (['"segment_manager::find( unique_instance_t* ) fails to compile"])].
6942   * [@https://svn.boost.org/trac/boost/ticket/10021 Trac #10021 (['"Interprocess and BOOST_USE_WINDOWS_H"])].
6943   * [@https://svn.boost.org/trac/boost/ticket/10230 Trac #10230 (['"No Sleep in interprocess::winapi"])].
6944   * [@https://github.com/boostorg/interprocess/pull/2 GitHub Pull #2] (['"Provide support for the Cray C++ compiler. The Cray compiler defines __GNUC__"]]).
6945   * [@https://github.com/boostorg/interprocess/pull/3 GitHub Pull #3] (['"Fix/mingw interprocess_exception throw in file_wrapper::priv_open_or_create"]]).
6946
6947*  [*ABI breaking]: [@https://svn.boost.org/trac/boost/ticket/9221 #9221] showed
6948   that `BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX` option of message queue,
6949   was completely broken so an ABI break was necessary to have a working implementation.
6950
6951*  Simplified, refactored and unified (timed_)lock code based on try_lock().
6952   There were several bugs when handling timeout expirations.
6953
6954*  Changed the implementation of condition variables' destructors to allow POSIX semantics
6955   (the condition variable can be destroyed after all waiting threads have been woken up)..
6956
6957*  Added `BOOST_INTERPROCESS_SHARED_DIR_PATH` option to define the shared directory used to place shared memory objects
6958   when implemented as memory mapped files.
6959
6960*  Added support for `BOOST_USE_WINDOWS_H`. When this macro is defined Interprocess does not declare
6961   used Windows API function and types, includes all needed windows SDK headers and uses types and
6962   functions declared by the Windows SDK.
6963
6964*  Added `get_size` to [classref ::boost:interprocess:windows_shared_memory].
6965
6966[endsect]
6967
6968[section:release_notes_boost_1_55_00 Boost 1.55 Release]
6969
6970*  Fixed bugs:
6971   * [@https://svn.boost.org/trac/boost/ticket/7156 #7156] (['"interprocess buffer streams leak memory on construction"]]).
6972   * [@https://svn.boost.org/trac/boost/ticket/7164 #7164] (['"Two potential bugs with b::int::vector of b::i::weak_ptr"]]).
6973   * [@https://svn.boost.org/trac/boost/ticket/7860 #7860] (['"smart_ptr's yield_k and spinlock utilities can improve spinlock-based sychronization primitives"]]).
6974   * [@https://svn.boost.org/trac/boost/ticket/8277 #8277] (['"docs for named_mutex erroneously refer to interprocess_mutex"]]).
6975   * [@https://svn.boost.org/trac/boost/ticket/8976 #8976] (['"shared_ptr fails to compile if used with a scoped_allocator"]]).
6976   * [@https://svn.boost.org/trac/boost/ticket/9008 #9008] (['"conditions variables fast enough only when opening a multiprocess browser"]]).
6977   * [@https://svn.boost.org/trac/boost/ticket/9065 #9065] (['"atomic_cas32 inline assembly wrong on ppc32"]]).
6978   * [@https://svn.boost.org/trac/boost/ticket/9073 #9073] (['"Conflict names 'realloc'"]]).
6979
6980[endsect]
6981
6982[section:release_notes_boost_1_54_00 Boost 1.54 Release]
6983
6984*  Added support for platform-specific flags to mapped_region (ticket #8030)
6985*  Fixed bugs:
6986   * [@https://svn.boost.org/trac/boost/ticket/7484 #7484],
6987   * [@https://svn.boost.org/trac/boost/ticket/7598 #7598],
6988   * [@https://svn.boost.org/trac/boost/ticket/7682 #7682],
6989   * [@https://svn.boost.org/trac/boost/ticket/7923 #7923],
6990   * [@https://svn.boost.org/trac/boost/ticket/7924 #7924],
6991   * [@https://svn.boost.org/trac/boost/ticket/7928 #7928],
6992   * [@https://svn.boost.org/trac/boost/ticket/7936 #7936],
6993   * [@https://svn.boost.org/trac/boost/ticket/8521 #8521],
6994   * [@https://svn.boost.org/trac/boost/ticket/8595 #8595].
6995
6996*  [*ABI breaking]: Changed bootstamp function in Windows to use EventLog service start time
6997   as system bootup time. Previously used `LastBootupTime` from WMI was unstable with
6998   time synchronization and hibernation and unusable in practice. If you really need
6999   to obtain pre Boost 1.54 behaviour define `BOOST_INTERPROCESS_BOOTSTAMP_IS_LASTBOOTUPTIME`
7000   from command line or `detail/workaround.hpp`.
7001
7002[endsect]
7003
7004[section:release_notes_boost_1_53_00 Boost 1.53 Release]
7005
7006*  Fixed GCC -Wshadow warnings.
7007*  Experimental multiple allocation interface improved and changed again. Still unstable.
7008*  Replaced deprecated BOOST_NO_XXXX with newer BOOST_NO_CXX11_XXX macros.
7009*  [*ABI breaking]: changed node pool allocators internals for improved efficiency.
7010*  Fixed bug [@https://svn.boost.org/trac/boost/ticket/7795 #7795].
7011
7012[endsect]
7013
7014[section:release_notes_boost_1_52_00 Boost 1.52 Release]
7015
7016*  Added `shrink_by` and `advise` functions in `mapped_region`.
7017*  [*ABI breaking:] Reimplemented `message_queue` with a circular buffer index (the
7018   old behavior used an ordered array, leading to excessive copies). This
7019   should greatly increase performance but breaks ABI. Old behaviour/ABI can be used
7020   undefining macro `BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX` in `boost/interprocess/detail/workaround.hpp`
7021*  Improved `message_queue` insertion time avoiding priority search for common cases
7022   (both array and circular buffer configurations).
7023*  Implemented `interproces_sharable_mutex` and `interproces_condition_any`.
7024*  Improved `offset_ptr` performance.
7025*  Added integer overflow checks.
7026
7027[endsect]
7028
7029[section:release_notes_boost_1_51_00 Boost 1.51 Release]
7030
7031*  Synchronous and asynchronous flushing for `mapped_region::flush`.
7032*  [*Source & ABI breaking]: Removed `get_offset` method from `mapped_region` as
7033   it has no practical utility and `m_offset` member was not for anything else.
7034*  [*Source & ABI breaking]: Removed `flush` from `managed_shared_memory`.
7035   as it is unspecified according to POSIX:
7036   [@http://pubs.opengroup.org/onlinepubs/009695399/functions/msync.html
7037   ['"The effect of msync() on a shared memory object or a typed memory object is unspecified"] ].
7038*  Fixed bug
7039  [@https://svn.boost.org/trac/boost/ticket/7152 #7152],
7040
7041[endsect]
7042
7043[section:release_notes_boost_1_50_00 Boost 1.50 Release]
7044
7045*  Fixed bugs
7046  [@https://svn.boost.org/trac/boost/ticket/3750 #3750],
7047  [@https://svn.boost.org/trac/boost/ticket/6727 #6727],
7048  [@https://svn.boost.org/trac/boost/ticket/6648 #6648],
7049
7050*  Shared memory in windows has again kernel persistence: kernel bootstamp
7051   and WMI has received some fixes and optimizations. This causes incompatibility
7052   with Boost 1.48 and 1.49 but the user can comment `#define BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME`
7053   in the windows configuration part to get Boost 1.48 & Boost 1.49 behaviour.
7054
7055[endsect]
7056
7057[section:release_notes_boost_1_49_00 Boost 1.49 Release]
7058
7059*  Fixed bugs
7060  [@https://svn.boost.org/trac/boost/ticket/6531 #6531],
7061  [@https://svn.boost.org/trac/boost/ticket/6412 #6412],
7062  [@https://svn.boost.org/trac/boost/ticket/6398 #6398],
7063  [@https://svn.boost.org/trac/boost/ticket/6340 #6340],
7064  [@https://svn.boost.org/trac/boost/ticket/6319 #6319],
7065  [@https://svn.boost.org/trac/boost/ticket/6287 #6287],
7066  [@https://svn.boost.org/trac/boost/ticket/6265 #6265],
7067  [@https://svn.boost.org/trac/boost/ticket/6233 #6233],
7068  [@https://svn.boost.org/trac/boost/ticket/6147 #6147],
7069  [@https://svn.boost.org/trac/boost/ticket/6134 #6134],
7070  [@https://svn.boost.org/trac/boost/ticket/6058 #6058],
7071  [@https://svn.boost.org/trac/boost/ticket/6054 #6054],
7072  [@https://svn.boost.org/trac/boost/ticket/5772 #5772],
7073  [@https://svn.boost.org/trac/boost/ticket/5738 #5738],
7074  [@https://svn.boost.org/trac/boost/ticket/5622 #5622],
7075  [@https://svn.boost.org/trac/boost/ticket/5552 #5552],
7076  [@https://svn.boost.org/trac/boost/ticket/5518 #5518],
7077  [@https://svn.boost.org/trac/boost/ticket/4655 #4655],
7078  [@https://svn.boost.org/trac/boost/ticket/4452 #4452],
7079  [@https://svn.boost.org/trac/boost/ticket/4383 #4383],
7080  [@https://svn.boost.org/trac/boost/ticket/4297 #4297].
7081
7082* Fixed timed functions in mutex implementations to fulfill POSIX requirements:
7083   ['Under no circumstance shall the function fail with a timeout if the mutex can be locked
7084     immediately. The validity of the abs_timeout parameter need not be checked if the mutex
7085     can be locked immediately.]
7086
7087[endsect]
7088
7089[section:release_notes_boost_1_48_00 Boost 1.48 Release]
7090
7091*  Fixed bugs
7092  [@https://svn.boost.org/trac/boost/ticket/2796 #2796],
7093  [@https://svn.boost.org/trac/boost/ticket/4031 #4031],
7094  [@https://svn.boost.org/trac/boost/ticket/4251 #4251],
7095  [@https://svn.boost.org/trac/boost/ticket/4452 #4452],
7096  [@https://svn.boost.org/trac/boost/ticket/4895 #4895],
7097  [@https://svn.boost.org/trac/boost/ticket/5077 #5077],
7098  [@https://svn.boost.org/trac/boost/ticket/5120 #5120],
7099  [@https://svn.boost.org/trac/boost/ticket/5123 #5123],
7100  [@https://svn.boost.org/trac/boost/ticket/5230 #5230],
7101  [@https://svn.boost.org/trac/boost/ticket/5197 #5197],
7102  [@https://svn.boost.org/trac/boost/ticket/5287 #5287],
7103  [@https://svn.boost.org/trac/boost/ticket/5294 #5294],
7104  [@https://svn.boost.org/trac/boost/ticket/5306 #5306],
7105  [@https://svn.boost.org/trac/boost/ticket/5308 #5308],
7106  [@https://svn.boost.org/trac/boost/ticket/5392 #5392],
7107  [@https://svn.boost.org/trac/boost/ticket/5409 #5409],
7108
7109* Added support to customize offset_ptr and allow
7110  creating custom managed segments that might be shared between
7111  32 and 64 bit processes.
7112
7113*  Shared memory in windows has again filesystem lifetime: kernel bootstamp
7114   and WMI use to get a reliable timestamp was causing a lot of trouble.
7115
7116[endsect]
7117
7118[section:release_notes_boost_1_46_00 Boost 1.46 Release]
7119
7120*  Fixed bugs
7121  [@https://svn.boost.org/trac/boost/ticket/4557 #4557],
7122  [@https://svn.boost.org/trac/boost/ticket/4979 #4979],
7123  [@https://svn.boost.org/trac/boost/ticket/4907 #4907],
7124  [@https://svn.boost.org/trac/boost/ticket/4895 #4895].
7125
7126[endsect]
7127
7128[section:release_notes_boost_1_45_00 Boost 1.45 Release]
7129
7130*  Fixed bugs
7131  [@https://svn.boost.org/trac/boost/ticket/1080 #1080],
7132  [@https://svn.boost.org/trac/boost/ticket/3284 #3284],
7133  [@https://svn.boost.org/trac/boost/ticket/3439 #3439],
7134  [@https://svn.boost.org/trac/boost/ticket/3448 #3448],
7135  [@https://svn.boost.org/trac/boost/ticket/3582 #3582],
7136  [@https://svn.boost.org/trac/boost/ticket/3682 #3682],
7137  [@https://svn.boost.org/trac/boost/ticket/3829 #3829],
7138  [@https://svn.boost.org/trac/boost/ticket/3846 #3846],
7139  [@https://svn.boost.org/trac/boost/ticket/3914 #3914],
7140  [@https://svn.boost.org/trac/boost/ticket/3947 #3947],
7141  [@https://svn.boost.org/trac/boost/ticket/3950 #3950],
7142  [@https://svn.boost.org/trac/boost/ticket/3951 #3951],
7143  [@https://svn.boost.org/trac/boost/ticket/3985 #3985],
7144  [@https://svn.boost.org/trac/boost/ticket/4010 #4010],
7145  [@https://svn.boost.org/trac/boost/ticket/4417 #4417],
7146  [@https://svn.boost.org/trac/boost/ticket/4019 #4019],
7147  [@https://svn.boost.org/trac/boost/ticket/4039 #4039],
7148  [@https://svn.boost.org/trac/boost/ticket/4218 #4218],
7149  [@https://svn.boost.org/trac/boost/ticket/4230 #4230],
7150  [@https://svn.boost.org/trac/boost/ticket/4250 #4250],
7151  [@https://svn.boost.org/trac/boost/ticket/4297 #4297],
7152  [@https://svn.boost.org/trac/boost/ticket/4350 #4350],
7153  [@https://svn.boost.org/trac/boost/ticket/4352 #4352],
7154  [@https://svn.boost.org/trac/boost/ticket/4426 #4426],
7155  [@https://svn.boost.org/trac/boost/ticket/4516 #4516],
7156  [@https://svn.boost.org/trac/boost/ticket/4524 #4524],
7157  [@https://svn.boost.org/trac/boost/ticket/4557 #4557],
7158  [@https://svn.boost.org/trac/boost/ticket/4606 #4606],
7159  [@https://svn.boost.org/trac/boost/ticket/4685 #4685],
7160  [@https://svn.boost.org/trac/boost/ticket/4694 #4694].
7161
7162*  Added support for standard rvalue reference move semantics
7163   (tested on GCC 4.5 and VC10).
7164
7165*  Permissions can be detailed for interprocess named resources.
7166
7167*  `mapped_region::flush` initiates disk flushing but does not guarantee it's completed
7168   when returns, since it is not portable.
7169
7170*  FreeBSD and MacOS now use posix semaphores to implement named semaphores and mutex.
7171
7172[endsect]
7173
7174[section:release_notes_boost_1_41_00 Boost 1.41 Release]
7175
7176*  Support for POSIX shared memory in Mac OS.
7177*  [*ABI breaking]: Generic `semaphore` and `named_semaphore` now implemented more efficiently with atomic operations.
7178*  More robust file opening in Windows platforms with active Anti-virus software.
7179
7180[endsect]
7181
7182[section:release_notes_boost_1_40_00 Boost 1.40 Release]
7183
7184*  Windows shared memory is created in Shared Documents folder so that it can be shared
7185   between services and processes
7186*  Fixed bugs
7187  [@https://svn.boost.org/trac/boost/ticket/2967 #2967],
7188  [@https://svn.boost.org/trac/boost/ticket/2973 #2973],
7189  [@https://svn.boost.org/trac/boost/ticket/2992 #2992],
7190  [@https://svn.boost.org/trac/boost/ticket/3138 #3138],
7191  [@https://svn.boost.org/trac/boost/ticket/3166 #3166],
7192  [@https://svn.boost.org/trac/boost/ticket/3205 #3205].
7193
7194[endsect]
7195
7196[section:release_notes_boost_1_39_00 Boost 1.39 Release]
7197
7198*  Added experimental `stable_vector` container.
7199*  `shared_memory_object::remove` has now POSIX `unlink` semantics and
7200   `file_mapping::remove` was added to obtain POSIX `unlink` semantics with mapped files.
7201*  Shared memory in windows has now kernel lifetime instead of filesystem lifetime: shared
7202   memory will disappear when the system reboots.
7203*  Updated move semantics.
7204*  Fixed bugs
7205  [@https://svn.boost.org/trac/boost/ticket/2722 #2722],
7206  [@https://svn.boost.org/trac/boost/ticket/2729 #2729],
7207  [@https://svn.boost.org/trac/boost/ticket/2766 #2766],
7208  [@https://svn.boost.org/trac/boost/ticket/1390 #1390],
7209  [@https://svn.boost.org/trac/boost/ticket/2589 #2589],
7210
7211[endsect]
7212
7213[section:release_notes_boost_1_38_00 Boost 1.38 Release]
7214
7215*  Updated documentation to show rvalue-references funcions instead of emulation functions.
7216*  More non-copyable classes are now movable.
7217*  Move-constructor and assignments now leave moved object in default-constructed state
7218   instead of just swapping contents.
7219*  Several bugfixes (
7220  [@https://svn.boost.org/trac/boost/ticket/2391 #2391],
7221  [@https://svn.boost.org/trac/boost/ticket/2431 #2431],
7222  [@https://svn.boost.org/trac/boost/ticket/1390 #1390],
7223  [@https://svn.boost.org/trac/boost/ticket/2570 #2570],
7224  [@https://svn.boost.org/trac/boost/ticket/2528 #2528].
7225
7226[endsect]
7227
7228[section:release_notes_boost_1_37_00 Boost 1.37 Release]
7229
7230*  Containers can be used now in recursive types.
7231*  Added `BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION` macro option to force the use
7232   of generic emulation code for process-shared synchronization primitives instead of
7233   native POSIX functions.
7234*  Added placement insertion members to containers
7235*  `boost::posix_time::pos_inf` value is now handled portably for timed functions.
7236*  Update some function parameters from `iterator` to `const_iterator` in containers
7237   to keep up with the draft of the next standard.
7238*  Documentation fixes.
7239
7240[endsect]
7241
7242[section:release_notes_boost_1_36_00 Boost 1.36 Release]
7243
7244*  Added anonymous shared memory for UNIX systems.
7245*  Fixed erroneous `void` return types from `flat_map::erase()` functions.
7246*  Fixed missing move semantics on managed memory classes.
7247*  Added copy_on_write and open_read_only options for shared memory and mapped file managed classes.
7248*  [*ABI breaking]: Added to `mapped_region` the mode used to create it.
7249*  Corrected instantiation errors in void allocators.
7250*  `shared_ptr` is movable and supports aliasing.
7251
7252[endsect]
7253
7254[section:release_notes_boost_1_35_00 Boost 1.35 Release]
7255
7256*  Added auxiliary utilities to ease the definition and construction of
7257   [classref boost::interprocess::shared_ptr shared_ptr],
7258   [classref boost::interprocess::weak_ptr weak_ptr] and
7259   `unique_ptr`. Added explanations
7260   and examples of these smart pointers in the documentation.
7261
7262*  Optimized vector:
7263   * 1) Now works with raw pointers as much as possible when
7264   using allocators defining `pointer` as an smart pointer. This increases
7265   performance and improves compilation times.
7266   * 2) A bit of metaprogramming
7267   to avoid using move_iterator when the type has trivial copy constructor
7268   or assignment and improve performance.
7269   * 3) Changed custom algorithms
7270   with standard ones to take advantage of optimized standard algorithms.
7271   * 4) Removed unused code.
7272
7273*  [*ABI breaking]: Containers don't derive from allocators, to avoid problems with allocators
7274   that might define virtual functions with the same names as container
7275   member functions. That would convert container functions in virtual functions
7276   and might disallow some of them if the returned type does not lead to a covariant return.
7277   Allocators are now stored as base classes of internal structs.
7278
7279*  Implemented [classref boost::interprocess::named_mutex named_mutex] and
7280   [classref boost::interprocess::named_semaphore named_semaphore] with POSIX
7281   named semaphores in systems supporting that option.
7282   [classref boost::interprocess::named_condition named_condition] has been
7283   accordingly changed to support interoperability with
7284   [classref boost::interprocess::named_mutex named_mutex].
7285
7286*  Reduced template bloat for node and adaptive allocators extracting node
7287   implementation to a class that only depends on the memory algorithm, instead of
7288   the segment manager + node size + node number...
7289
7290*  Fixed bug in `mapped_region` in UNIX when mapping address was provided but
7291   the region was mapped in another address.
7292
7293*  Added `aligned_allocate` and `allocate_many` functions to managed memory segments.
7294
7295*  Improved documentation about managed memory segments.
7296
7297*  [*Boost.Interprocess] containers are now documented in the Reference section.
7298
7299*  Correction of typos and documentation errors.
7300
7301*  Added `get_instance_name`, `get_instance_length` and `get_instance_type` functions
7302   to managed memory segments.
7303
7304*  Corrected suboptimal buffer expansion bug in `rbtree_best_fit`.
7305
7306*  Added iteration of named and unique objects in a segment manager.
7307
7308*  Fixed leak in [classref boost::interprocess::vector vector].
7309
7310*  Added support for Solaris.
7311
7312*  Optimized [classref boost::interprocess::segment_manager segment_manager]
7313   to avoid code bloat associated with templated instantiations.
7314
7315*  Fixed bug for UNIX: No slash ('/') was being added as the first character
7316   for shared memory names, leading to errors in some UNIX systems.
7317
7318*  Fixed bug in VC-8.0: Broken function inlining in core offset_ptr functions.
7319
7320*  Code examples changed to use new BoostBook code import features.
7321
7322*  Added aligned memory allocation function to memory algorithms.
7323
7324*  Fixed bug in `deque::clear()` and `deque::erase()`, they were declared private.
7325
7326*  Fixed bug in `deque::erase()`. Thanks to Steve LoBasso.
7327
7328*  Fixed bug in `atomic_dec32()`. Thanks to Glenn Schrader.
7329
7330*  Improved (multi)map/(multi)set constructors taking iterators. Now those have
7331   linear time if the iterator range is already sorted.
7332
7333*  [*ABI breaking]: (multi)map/(multi)set now reduce their node size. The color
7334   bit is embedded in the parent pointer. Now, the size of a node is the size of
7335   3 pointers in most systems. This optimization is activated for raw and `offset_ptr`
7336   pointers.
7337
7338*  (multi)map/(multi)set now reuse memory from old nodes in the assignment operator.
7339
7340*  [*ABI breaking]: Implemented node-containers based on intrusive containers.
7341   This saves code size, since many instantiations share the same algorithms.
7342
7343*  Corrected code to be compilable with Visual C++ 8.0.
7344
7345*  Added function to zero free memory in memory algorithms and the segment manager.
7346   This function is useful for security reasons and to improve compression ratios
7347   for files created with `managed_mapped_file`.
7348
7349*  Added support for intrusive index types in managed memory segments.
7350   Intrusive indexes save extra memory allocations to allocate the index
7351   since with just one
7352   allocation, we allocate room for the value, the name and the hook to insert
7353   the object in the index.
7354
7355*  Created new index type: [*iset_index]. It's an index based on
7356   an intrusive set (rb-tree).
7357
7358*  Created new index type: [*iunordered_set_index]. It's an index
7359   based on a pseudo-intrusive unordered set (hash table).
7360
7361*  [*ABI breaking]: The intrusive index [*iset_index] is now the default
7362   index type.
7363
7364*  Optimized vector to take advantage of `boost::has_trivial_destructor`.
7365   This optimization avoids calling destructors of elements that have a trivial destructor.
7366
7367*  Optimized vector to take advantage of `has_trivial_destructor_after_move` trait.
7368   This optimization avoids calling destructors of elements that have a trivial destructor
7369   if the element has been moved (which is the case of many movable types). This trick
7370   was provided by Howard Hinnant.
7371
7372*  Added security check to avoid integer overflow bug in allocators and
7373   named construction functions.
7374
7375*  Added alignment checks to forward and backwards expansion functions.
7376
7377*  Fixed bug in atomic functions for PPC.
7378
7379*  Fixed race-condition error when creating and opening a managed segment.
7380
7381*  Added adaptive pools.
7382
7383*  [*Source breaking]: Changed node allocators' template parameter order
7384   to make them easier to use.
7385
7386*  Added support for native windows shared memory.
7387
7388*  Added more tests.
7389
7390*  Corrected the presence of private functions in the reference section.
7391
7392*  Added function (`deallocate_free_chunks()`) to manually deallocate completely free
7393   chunks from node allocators.
7394
7395*  Implemented N1780 proposal to LWG issue 233: ['Insertion hints in associative containers]
7396   in interprocess [classref boost::interprocess::multiset multiset] and
7397   [classref boost::interprocess::multimap multimap] classes.
7398
7399*  [*Source breaking]: A shared memory object is now used including
7400   `shared_memory_object.hpp` header instead of `shared memory.hpp`.
7401
7402*  [*ABI breaking]: Changed global mutex when initializing managed shared memory
7403   and memory mapped files. This change tries to minimize deadlocks.
7404
7405*  [*Source breaking]: Changed shared memory, memory mapped files and mapped region's
7406   open mode to a single `mode_t` type.
7407
7408*  Added extra WIN32_LEAN_AND_MEAN before including DateTime headers to avoid socket
7409   redefinition errors when using Interprocess and Asio in windows.
7410
7411*  [*ABI breaking]: `mapped_region` constructor no longer requires classes
7412   derived from memory_mappable, but classes must fulfill the MemoryMappable concept.
7413
7414*  Added in-place reallocation capabilities to basic_string.
7415
7416*  [*ABI breaking]: Reimplemented and optimized small string optimization. The narrow
7417   string class has zero byte overhead with an internal 11 byte buffer in 32 systems!
7418
7419*  Added move semantics to containers. Improves
7420   performance when using containers of containers.
7421
7422*  [*ABI breaking]: End nodes of node containers (list, slist, map/set) are now
7423   embedded in the containers instead of allocated using the allocator. This
7424   allows no-throw move-constructors and improves performance.
7425
7426*  [*ABI breaking]: [*slist] and [*list] containers now have constant-time
7427   ['size()] function. The size of the container is added as a member.
7428
7429[endsect]
7430
7431[endsect]
7432
7433[section:books_and_links Books and interesting links]
7434
7435Some useful references about the C++ programming language, C++ internals,
7436shared memory, allocators and containers used to design [*Boost.Interprocess].
7437
7438[section:references_books Books]
7439
7440* Great book about multithreading, and POSIX: [*['"Programming with Posix Threads"]],
7441  [*David R. Butenhof]
7442
7443* The UNIX inter-process bible: [*['"UNIX Network Programming, Volume 2: Interprocess Communications"]],
7444  [*W. Richard Stevens]
7445
7446* Current STL allocator issues: [*['"Effective STL"]], [*Scott Meyers]
7447
7448* My C++ bible: [*['"Thinking in C++, Volume 1 & 2"]], [*Bruce Eckel and Chuck Allison]
7449
7450* The book every C++ programmer should read: [*['"Inside the C++ Object Model"]], [*Stanley B. Lippman]
7451
7452* A must-read: [*['"ISO/IEC TR 18015: Technical Report on C++ Performance"]], [*ISO WG21-SC22 members.]
7453
7454[endsect]
7455
7456[section:references_links Links]
7457
7458* A framework to put the STL in shared memory: [@http://allocator.sourceforge.net/ ['"A C++ Standard Allocator for the Standard Template Library"] ].
7459
7460* Instantiating C++ objects in shared memory: [@http://www.cs.ubc.ca/local/reading/proceedings/cascon94/htm/english/abs/hon.htm ['"Using objects in shared memory for C++ application"] ].
7461
7462* A shared memory allocator and relative pointer: [@http://home.earthlink.net/~joshwalker1/writing/SharedMemory.html ['"Taming Shared Memory"] ].
7463
7464[endsect]
7465
7466[endsect]
7467
7468[section:future_improvements Future improvements...]
7469
7470There are some Interprocess features that I would like to implement and some
7471[*Boost.Interprocess] code that can be much better. Let's see some ideas:
7472
7473[section:win32_sync Win32 synchronization is too basic]
7474
7475Win32 version of shared mutexes and shared conditions are based on "spin and wait"
7476atomic instructions. This leads to poor performance and does not manage any issues
7477like priority inversions. We would need very serious help from threading experts on
7478this. And I'm not sure that this can be achieved in user-level software. Posix based
7479implementations use PTHREAD_PROCESS_SHARED attribute to place mutexes in shared memory,
7480so there are no such problems. I'm not aware of any implementation that simulates
7481PTHREAD_PROCESS_SHARED attribute for Win32. We should be able to construct these
7482primitives in memory mapped files, so that we can get filesystem persistence just like
7483with POSIX primitives.
7484
7485[endsect]
7486
7487[section:future_objectnames Use of wide character names on Boost.Interprocess basic resources]
7488
7489Currently Interprocess only allows *char* based names for basic named
7490objects. However, several operating systems use *wchar_t* names for resources
7491(mapped files, for example).
7492In the future Interprocess should try to present a portable narrow/wide char interface.
7493To do this, it would be useful to have a boost wstring <-> string conversion
7494utilities to translate resource names (escaping needed characters
7495that can conflict with OS names) in a portable way. It would be interesting also
7496the use of [*boost::filesystem] paths to avoid operating system specific issues.
7497
7498[endsect]
7499
7500[section:future_security Security attributes]
7501
7502[*Boost.Interprocess] does not define security attributes for shared memory and
7503synchronization objects. Standard C++ also ignores security attributes with files
7504so adding security attributes would require some serious work.
7505
7506[endsect]
7507
7508[section:future_ipc Future inter-process communications]
7509
7510[*Boost.Interprocess] offers a process-shared message queue based on
7511[*Boost.Interprocess] primitives like mutexes and conditions. I would want to
7512develop more mechanisms, like stream-oriented named fifo so that we can use it
7513with a iostream-interface wrapper (we can imitate Unix pipes).
7514
7515C++ needs more complex mechanisms and it would be nice to have a stream and
7516datagram oriented PF_UNIX-like mechanism in C++. And for very fast inter-process
7517remote calls Solaris doors is an interesting alternative to implement for C++.
7518But the work to implement PF_UNIX-like sockets and doors would be huge
7519(and it might be difficult in a user-level library). Any network expert volunteer?
7520
7521[endsect]
7522
7523[endsect]
7524
7525[endsect]
7526
7527[section:indexes_reference Indexes and Reference]
7528
7529[section:index Indexes]
7530
7531[include auto_index_helpers.qbk]
7532
7533[named_index class_name Class Index]
7534[named_index typedef_name Typedef Index]
7535[named_index function_name Function Index]
7536[/named_index macro_name Macro Index]
7537[/index]
7538
7539[endsect]
7540
7541[xinclude autodoc.xml]
7542
7543[endsect]
7544