2012-04-06 73 views
0

我需要一个静态变量指向自己在引用线程方法中的对象时使用。我正在尝试在process.h中使用_beginthread方法。此类型的许多对象将使用线程方法。目前这是失败的,因为实例变量在整个类中共享。我需要实例变量是静态的,以便在threadLoop中使用并需要它引用该对象。有什么建议么?多个对象的静态实例变量 - C++

部首:static Nodes *instance;

实现:Nodes *Nodes::instance = NULL;

main.cpp中:

for(int c = 0; c < 7; c++) 
{ 
    nodesVect.push_back(Nodes(c, c+10)); 
} 

for(int c = 0; c < 7; c++) 
{ 
    nodesVect.at(c).init(); // init() { instance = this; } 
} 
+0

哪个对象? 7个节点应该是每个线程的一个吗? – bitmask 2012-04-06 01:16:23

+0

你在问一个变量的线程特定实例吗?如果是这样,请尝试查看由线程ID索引的哈希表,或者使用线程本地存储。 – Rick 2012-04-06 01:25:50

回答

0

我_beginthreadex()的用法如下;

一个cStartable基类

virtual bool Start(int numberOfThreadsToSpawn); 
virtual bool Stop(); 
virtural int Run(cThread &myThread) = 0; 
//the magic... 
friend unsigned __stdcall threadfunc(void *pvarg); 
void StartableMain(); 

的MAJIC是:

unsigned __stdcall threadfunc(void *pvarg) 
{ 
    cStartable *pMe = reinterpret_cast<cStartable*>(pvarg); 
    pMe->StartableMain(); 
} 
void cStartable::StartableMain() 
{ 
    //Find my threadId in my threadMap 
    cThread *pMyThread = mThreadMap.find(GetCurrentThreadId()); 
    int rc = Run(pMyThread); 
} 
bool cStartable::Start() 
{ 
    cThread *pThread = new cThread(); 
    pThread->Init(); 
    mThreadMap.insert(tThreadMapData(pThread->mThreadId, pThread)); 
} 

和公用cThread类。

bool cThread::Init(cStartable *pStartable) 
{ 
    _beginthreadex(NULL, /*stack*/ 65535), &threadfunc, pStartable, /*initstate*/0, &mThreadId); 
    // now cThread has a unique bit of info that can match itself up within the startable's run. 
} 

的事情,需要一个线程启动的继承,并实现自己的运行。

class Node : public cStartable {} 

我在这里编了很多代码。它是非常强大和安静的强大,可以一次产生多个线程实例从一个对象中派生出来,并且在子类级别上它非常干净。

所有这一切的一点是,cNode :: Run()会传递每个线程实例对象的每个线程实例堆数据可以附加到的对象。否则所有线程实例将共享其单个类实例作为其“内存空间”。我喜欢它:) 如果您需要更多详情,我很乐意分享。