多个对象的静态实例变量 - c ++

时间:2012-04-06 00:53:52

标签: c++ multithreading static

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

标题: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;  }
}

1 个答案:

答案 0 :(得分: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.   
}

需要线程的东西从startable继承并实现它们的Run。

class Node : public cStartable {}

我在这里编辑了很多代码。它非常强大且安静,可以在一个对象上同时生成多个线程实例,并且在子类级别上非常干净。

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