Loss of performance in C ++ 0x and static local variables?

What is a realistic performance loss due to the fact that in C ++ 0x all other threads should wait in this case:

string& program_name() { static string instance = "Parallel Pi"; return instance; } 

Let's look at the optimal scenario: the programmer was very careful that even with 100 threads only the main thread calls the program_name function, all other 99 workflows are busy with useful things, which does not require calling this "critical" one.

I quote the new C ++ 0x-Std Β§ 6.7. (4) stmt.decl

... such an object is initialized when the first control passes through its declaration ... If the control enters the declaration simultaneously during the initialization of the object, simultaneous execution should wait for the initialization to complete ...

What are the realistic overheads that a real-world compiler needs to impose on me so that this static initialization is performed in accordance with the requirements of the standard.

  • Is a lock / mutex required? I assume that they are expensive, even if they are not needed?
  • If they are expensive, will this be done by less expensive mechanisms?

edit: added string ...

+4
source share
2 answers

If the control enters the declaration at the same time while the object is initializing, simultaneous execution should wait for the initialization to complete ...

I think this is a reasonable and very normal thing in parallel programming. In any case, this statement does not say that all other threads should wait for this initialization. They must wait in case to access the initialized object.

Is a lock / mutex required? I assume that they are expensive, even if they are not needed?

May be. Mutex / lock are not that expensive in fact, they are expensive only when a piece of locked code needs to be accessed by many, or even any, threads.

If they are expensive, will this be done by less expensive mechanisms?

There are also other non-blocking AFAIK solutions.

+2
source

If you are really worried about the price of locking, you can simply call the function before you start your workflows that initialize the static. If you call it after the start of the threads, either you or the compiler must arrange some type of lock, so there is no additional overhead.

+1
source

All Articles