C ++:多线程程序中的静态变量 [英] C++: Static variables in multithreaded program

查看:158
本文介绍了C ++:多线程程序中的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在多线程程序中有静态变量(特别是在函数中)有什么问题?

What is the problem with having static variables (especially within functions) in multithreaded programs?

谢谢。

推荐答案

要随机选择一个说明性示例,请使用 asctime 。原型如下:

To pick an illustrative example at random, take an interface like asctime in the C library. The prototype looks like this:

 char *
 asctime(const struct tm *timeptr);

这隐含必须有一些全局缓冲区来存储 char * 退回。最常见和简单的方法是:

This implicitly must have some global buffer to store the characters in the char* returned. The most common and simple way to accomplish this would be something like:

 char *
 asctime(const struct tm *timeptr)
 {
    static char buf[MAX_SIZE];

    /* TODO: convert timeptr into string */

    return buf;
 }

这在多线程环境中完全破坏,因为<$ c $每次调用 asctime()时,c> buf 将处于相同的地址。如果两个线程同时调用 asctime(),它们有可能覆盖彼此的结果。在 asctime()的合约中隐含的是,字符串的字符将持续到下一次调用 asctime()

This is totally broken in a multi-threaded environment, because buf will be at the same address for each call to asctime(). If two threads call asctime() at the same time, they run the risk of overwriting each other's results. Implicit in the contract of asctime() is that the characters of the string will stick around until the next call to asctime(), and concurrent calls breaks this.

有一些语言扩展通过线程本地存储( __ thread __ declspec(thread))。我相信这个想法使它成为C ++ 0x作为 thread_local 关键字。

There are some language extensions that work around this particular problem in this particular example via thread-local storage (__thread,__declspec(thread)). I believe this idea made it into C++0x as the thread_local keyword.

即使这样我会认为一个糟糕的设计决定,以这种方式使用它,出于类似的原因,为什么不好使用全局变量。其中,它可以被认为是对于呼叫者保持和提供这种状态而不是被呼叫者的更干净的接口。但是,这些是主观论据。

Even so I would argue it's a bad design decision to use it this way, for similar reasons as for why it's bad to use global variables. Among other things, it may be thought of as a cleaner interface for the caller to maintain and provide this kind of state, rather than the callee. These are subjective arguments, however.

这篇关于C ++:多线程程序中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆