我想定义一个全局变量,但是要求当不同线程访问时不会看到其他线程对它的修改,也就是说,这个变量只是在一个线程中看起来像是全局变量,实际上每一个线程都拥有它的副本并且只能看到和修改这个副本;但这个变量也不是线程的局部变量,因为这个变量不知道调用它的线程在何处启动,若用局部变量的话实现可能比较繁琐,所以我需要一个只在一个线程中看起来像是全局变量的变量,要实现这个目的该如何做呢?望高手指教!
语言层面做不到。每个线程的堆栈是独立的,但是共用堆,但是你可以通过一些技巧来实现,比如说用设计模式中的池模式。
维护一个线程id到对应存储的map,然后你的调用代码访问它,大致的伪代码如下:
class VarStore
{
private: static Map<int, int> _map;
public int getValue()
{
int threadid = 获取线程的id;
if (_map存在key(threadid)) {
return _map.get(threadid);
}
else {
_map.Add(threadid, 0);
return 0;
}
}
public: void setValue(int value)
{
int threadid = 获取线程的id;
if (_map存在key(threadid)) {
_map.set(threadid, value);
}
else {
_map.Add(threadid, 0);
return 0;
}
}
};
你可以尝试使用内联,或者直接在线程中访问map
定义一个变量,然后把拷贝对象作为参数传递给线程函数。这样每个线程都是访问的副本。
楼主实际上未真正掌握C++,你掌握的是C不是C++,多看看些相关的书吧
你用局部变量就好了,初始值为你全局变量的值。
为何不用局部变量呢?
你用局部变量就好了,初始值为你全局变量的值。
C++11在语言层面提供了楼主需要的功能。可以使用thread_local关键字。
The thread_local keyword is only allowed for objects declared at namespace scope, objects declared at block scope, and static data members. It indicates that the object has thread storage duration. It can be combined with static or extern to specify internal or external linkage (except for static data members which always have external linkage), respectively, but that additional static doesn't affect the storage duration.
详情参考:http://en.cppreference.com/w/cpp/language/storage_duration