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

static instance variable for multiple objects - c++

本文关键字:实例 变量 -c++ 静态 对象      更新时间:2023-10-16

在线程方法中引用对象时,我需要一个指向自身的静态变量。我正在尝试在process.h中使用_beginthread方法。许多这种类型的对象都将使用线程方法。目前,这是失败的,因为实例变量是在整个类中共享的。我需要实例变量是静态的,以便在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;  }
}

My _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();

主要是:

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()获得了一个每个线程实例对象,每个线程实例堆数据可以附加到该对象中。否则,所有线程实例共享它们的单个类实例作为它们的"内存空间"。我喜欢它:)如果你需要更多的细节,我很乐意与你分享。