Reputation: 119
I am having some trouble with multi threaded c++ code on windows.
class test
{
public:
bool flag;
test() {flag=true;}
void start_do(){while(flag) puts("doing...");}
void stop_do() {flag=0;}
}
int main()
{
test t;
HANDLE h=CreateThread(0,0,(LPTHREAD_START_ROUTINE)t.start_do,0,1,0);
Sleep(5000);
t.stop_do();
return 0;
}
I want to change the doing state with the flag. But it doesn't work. Could someone give me some help!
Upvotes: 1
Views: 7797
Reputation:
You can use <thread>
though.
cplusplus.com - <thread>
It can be a little hard to understand threads,cause I did.
But it will be easy if you look at the link I added.I think.
Upvotes: 0
Reputation: 26536
The entire code does not make much sense.
first of all, Windows API is a C api. C has no knowing of what a class or method is. C only knows global functions. so passing member function is the first mistake.
secondly, the member function you provided does not look like what CreateThread
expects to! you should supply a function with the signature DWORD __stdcall (void*)
, you function does not look like that at all. casting it by force will only make more troubles.
thirdly, the way to pass a member function is with the sintax &ClassName::functionName
. writing object.function
means nothing.
finally, C++ has much simpler way of creating threads , and using them as objects, not handles:
test t;
std::thread t([&]{ t.start_do(); });
now, I don't recommend using winapi for creating threads unless you have really good reason why (like specifying the stack size, and if the stack memory is reserved or commited, etc.)
for the sake of the disscution here, the way to make you example to work is by "flattening" the object into void*
and re-cast it back inside some global function:
DWORD __stdcall callStartDo(void* pObject){
auto object = reinterpret_cast<test*>(pObject);
if (object){
object->start_do();
}
return 0U;
}
//...
test t;
unsigned long threadID = 0U;
CreateThread(nullptr,0U,&callStartDo,&t,0,&threadID);
and again, this examle shows how to do it only, I strongly advice using std::thread
instead. (look at how much overhead is involved vs. the C++ way!)
Upvotes: 5