我创建了一个类,类的初始化函数创建了一个线程(调用CreateThread),我现在想声明这个类的多个对象,却因为CreateThread而失败,因为CreateThread创建的所有线程的首地址相同,也就是一个线程重复被创建。不知各位有没有遇到这样的问题,各位是如何解决的,谢谢
//base.h
Class Base
{
private:
HANDLE hThread;
public:
Base();
~Base();
};
//base.cpp
DWORD WINAPI ThreadProc(void* arg)
{
//////////////////
//add code
return 0;
}
Base::Base()
{
hThread=CreateThread(NULL,0,ThreadProc,this,0,NULL);
}Base A,B,C;
//base.h
Class Base
{
private:
HANDLE hThread;
public:
Base();
~Base();
};
//base.cpp
DWORD WINAPI ThreadProc(void* arg)
{
//////////////////
//add code
return 0;
}
Base::Base()
{
hThread=CreateThread(NULL,0,ThreadProc,this,0,NULL);
}Base A,B,C;
{
hThread=CreateThread(NULL,0,ThreadProc,this,0,NULL);
CloseHandle(hThread);
}
先定义一个空的指针
DWORD (WINAPI* ThreadProc)(void* arg);
在调用CreateThread之前先给线程代码(包括数据)分配内存,
(我计划用new,但是我不知道线程代码段的首地址和大小)。
然后把内存的首地址赋给ThreadProc,用完之后释放内存。
in win98, the last paremter can not is NULL
can create three thread.
your meaning is all thread use the address of ThreadProc?i don't think so!
DWORD WINAPI ThreadProc(void* arg)
{
while(1)
{
sleep(1000);
}
return 0;
}can create three thread too!
it's wrong!the code's address of the three threads is same( all is the adress of ThreadProc)
but the data's address is differnt.
所以CreateThread()函数标准的用法是,创建完后立即CloseHandle(),我很少看到程序员注意这个事情,而很多高级程序员也不知道此类问题。所以在这里说明一下。