开发者

Setting Global variables in thread

I need to ha开发者_如何学编程ve 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜