Note that there are some explanatory texts on larger screens.

plurals
  1. POOn the use of static const variable in multi-threaded environment
    primarykey
    data
    text
    <p>I am trying to understand a potential scenario and whether it is likely to be a problem.</p> <p>So I have a static function that is currently thread-safe. The function being like so:</p> <pre><code>static thread_safe_func() { ... process } </code></pre> <p>Now in this function, I add the following:</p> <pre><code>static thread_safe_func() { static const Class::NonThreadSafeClassName() *array[16] = { Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), } ... code continues here } </code></pre> <p>Now is it in itself thread-safe? The array will be initialized once for the entire duration of the application's life, so once the function thread_safe_func() has been called, and fully run, I would expect this to be thread-safe.</p> <p>The issue is obviously what could occur during the first calls, what would happen in a scenario where a thread calls thread_safe_func(), the initialization of the const array occurs, but before that initialization completes, another thread is calling thread_safe_func().</p> <p>Would a change to:</p> <pre><code>static ClassMutex lock = ClassMutex() static thread_safe_func() { lock.Lock() static const Class::NonThreadSafeClassName() *array[16] = { Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), } lock.Unlock() ... code continues here } </code></pre> <p>be worthwhile and guarantee that this code is now thread-safe?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload