多个对象的静态实例变量-c++
static instance variable for multiple objects - c++
在线程方法中引用对象时,我需要一个指向自身的静态变量。我正在尝试在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()获得了一个每个线程实例对象,每个线程实例堆数据可以附加到该对象中。否则,所有线程实例共享它们的单个类实例作为它们的"内存空间"。我喜欢它:)如果你需要更多的细节,我很乐意与你分享。
相关文章:
- 返回 C++ 中的指针实例变量
- 返回实例变量的c++方法可以访问变量中的数据,但不能更改它,但在编译时不会生成错误
- C++ 实例变量初始值设定项中的重复类型
- 为什么可以在没有实例变量的情况下访问静态回调方法中的静态成员变量?
- C++ 中实例变量的双冒号
- 我可以在没有任何实例变量的情况下使用 decltype 吗?
- OpenMP 私有类实例变量
- C 取消实例变量指针
- 在C++私有区域中初始化实例变量
- 如何将指针存储在实例变量中,该指针被声明为指向基类的指针
- 如何在Arduino中创建另一个类库的实例变量
- 单元测试呼叫实例变量的函数
- 为构造函数初始化引用实例变量提供默认值
- 如何使编译器在实例变量未初始化时C++生成错误或警告
- 如何超载分配运算符,该操作员总计两个实例变量
- C++:通过引用传递或使用私有实例变量
- 对象作为类内的实例变量
- 在不构造实例变量的情况下C++声明实例变量的好方法是什么?
- 实例变量列表中的对象未被保留?指针问题
- Asio完成处理程序中的实例变量无效