Setting global variables in a stream

I need a string as a global variable. It is possible for multiple threads to set a global variable. Should I go for a mutex for this? Or the OS will handle such actions. Switching to mutexes affects application performance.

I'm not worried about the course of action. I am afraid of data corruption. Can anyone tell me about this.

+3
source share
4 answers

You seem to understand all the problems. If a global variable can get corrupted, you definitely need to lock it in the mutex. This will affect performance because this part will by definition now be synchronous. In this case, you will need to block the smallest part of the code as necessary, in order to minimize the time of calling the synchronous code.

+1
source

What is your global variable? Pointer to a string buffer or the buffer itself?

On many architectures (including the 32-bit x86 AFAIR), rewriting a single pointer is atomic.

This example might work:

volatile char **global_var;

void set_var(char *str) {
    char *tmp = strdup(str);
    global_var = &tmp;
}
0
source

Thread-Local Storage .
, C99, C1X. , (GCC, ICC Visual C).

0

Regarding standards, yes, you should use a mutex. Failure to do so will result in undefined behavior. In practice, most machine architectures will not have any problems with this. Future versions of the C (C1x) standard will have atomic types, which, if used here, will definitely do the job without blocking (although it is possible, using an internal lock, on broken arches that do not have real atomism).

0
source

All Articles