Markos.Perrakis@tsx.com wrote:
I have created a shared memory segment with the *boost::interprocess* library and have created and populated a *boost::interprocess::map* in that segment. The key for the map is the *boost::interprocess::string* class.
If I want to search for an element in the map I obviously have to supply the key for the element. Here is what I do:
{ std::string key; // assign here a value to key string object
const Char_Alloc char_alloc( (shared_memory_segment_obj.get_segment_manager() ) ); boost::interprocess::string some_string( char_alloc );
some_string.assign( key.c_str() ); }
where *Char_Alloc *is a suitable shared memory allocator for plain characters.
Can't you just assign directly to the shared memory string? { const Char_Alloc char_alloc( (shared_memory_segment_obj.get_segment_manager() ) ); boost::interprocess::string some_string( char_alloc ); some_string.insert(...); }
As you can see from the code the key (the some_string object) for the map is created in local memory (in-process memory) but the contents of the string are allocated in shared memory.
Yes. sizeof(some_string) bytes are in the stack, the dynamically allocated buffer in shared memory. I admit this is a bit annoying, but you can and I would try to offer a better alternative for this, maybe following Intrusive practica of offering overloaded find, count, lower_bound taking an external key type that is comparable with the internal one. But expect to see it in Boost 1.38/39 ;-)
If two threads access this shared memory segment and execute the above code at the same time, is this thread safe? Will the two concurrent *assign()* statements use the same location in shared memory and cause overlaps? Or is the shared memory allocator smart enough to synchronize the two *assign() *calls and execute them sequencially?
It's thread-safe. Think about shared memory as the same as a call to new[](). If to threads do this, they are thread-safe because each string obtains a different buffer. The same happens for shared memory, each string will allocate a different buffer. It would be different if the some_string itself was in shared memory, just like if you access to the very same std::string from two different threads. Regards, Ion