Conversation

Thread safety with UnicodeString type [Edit]

(overview of excerpts from articles in conversation)

Newsgroup: embarcadero.public.cppbuilder.language.cpp

# Lines
wrote on 15-May-2013:

I am considering using UnicodeString in threaded program so thread safety comes to mind.
Let's suppose you have a structure like this:
{code}
struct TTaskListEntry
{
75
  
Remy Lebeau (TeamB) replied on 15-May-2013:

John wrote:
  (snip)

UnicodeString reference counting will work just fine. You don't have to
  worry about protecting it.
  (snip)

When you access a UnicodeString via a 'const' reference, the UnicodeString's
  reference count is not incremented. That much is true. But its data payload
64
    
John May replied on 15-May-2013:

(snip)

Does this mean that reference counting increase/decrease is thread-safe (or perhaps atomic operation?) even though the actual UnicodeString data payload management isn't?
    I did test accessing data from 2 threads when it was being written from one and read from another and I do get access violation so it doesn't seem thread safe, and it is kind of odd to me that reference counting is exception to that. And does this depend on version of C++ Builder (I use 2010 version)?
    
    
    
25
      
Remy Lebeau (TeamB) replied on 15-May-2013:

John wrote:
      (snip)

Yes. String reference counts are protected by the RTL itself using its own
      locks.
      (snip)
Only one thread can create a new string payload, and it is initialized with
      a reference count of 1. Only one thread can decrement the reference count
32
        
John May replied on 16-May-2013:

OK here is some example code. It is actually "out of memory" and "invalid pointer operation".
        The example below works without errors (when Button1 is clicked that is). But if you don't wrap shared variable (SupposedToBeThreadSafe) in ProtectWrite and ProtectRead functions (as in commented lines) you should get errors above.
        {code}
        //---------------------------------------------------------------------------
        #include
97
          
Remy Lebeau (TeamB) replied on 16-May-2013:

John wrote:
          (snip)

Assigning a string to another string is thread-safe. Concatenating a string
          to another string is not. Concatenation requires multiple steps (reading
          string lengths, allocating memory, copying string characters), and the strings
          being concatenated could be modified by another thread while the concatenation
27
            
John May replied on 16-May-2013:

OK, thanks. Great answers, as usual!
            
            
            
            
1
FYI: Phrase searches are enclosed in either single or double quotes
 
 
Originally created by
Tamarack Associates
Thu, 14 Nov 2024 06:42:34 UTC
Copyright © 2009-2024
HREF Tools Corp.