简体   繁体   中英

Setting Global variables in thread

I need to have a string as a global variable. There is a possibility for multiple threads to set the global variable. Should I have to go for mutex for this? Or will OS handle such actions. Going for mutex affects the application performance.

I am not concerned about the order of actions happening. I am afraid of the data corruption. Could somebody let me know about this.

It sounds like you understand all of the concerns. If the global variable can be corrupt you definitely need to lock it in a mutex. This will affect performance, since this part is by definition now going to be synchronous. That being said, you will want to lock the smallest part of the code as necessary, to minimize the time that synchronous code is being called.

What's your global variable? A pointer to the string buffer, or the buffer itself?

On many architectures (including AFAIR 32-bit x86) overwriting 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;
}

You can use Thread-Local Storage for this.
Unfortunately, its not specified in current C99 standart, but possible will be there in C1X. For now, you can use compiler-specific implementations (GCC, ICC and Visual C have it).

As far as the standards are concerned, yes, you must use a mutex. Failure to do so results in undefined behavior. In practice, most machine architectures will have no problem with this. Future versions of the C standard (C1x) will have atomic types which, if used here, would definitely make the assignment without lock safe (albeit possibly using an internal lock, on broken archs that lack real atomics).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM