I would like to implement a sleep() function in my thread class, but I don't know if this is a valid/proper way to do it. This is my entire thread class (thread.h):
开发者_如何学C#include <process.h>
struct RUNNABLE{
virtual void run() = 0;
};
class thread{
public:
void start(void *ptr){
DWORD thr_id;
HANDLE thr_handl = (HANDLE)_beginthreadex(NULL, 0, thread_proc, ptr, 0, (unsigned int*)&thr_id);
}
void sleep(int sleep_time, bool alertable){
SleepEx(sleep_time, alertable);
}
private:
static unsigned int __stdcall thread_proc(void *param){
((RUNNABLE*)param)->run();
_endthreadex(0);
return 0;
}
};
And as you're probably able to sort out, this is my sleep() function:
void sleep(int sleep_time, bool alertable){
SleepEx(sleep_time, alertable);
}
But will this make the actual thread contained inside this thread instance sleep for the specified amount of milliseconds?
Best regards, Benjamin :).
EDIT:
So according to atzz, I could define the sleep function as a static member function, and have that call ::SleepEx(), and that would allow me to call it like this:
class test : RUNNABLE{
virtual void run(){
printf("hi");
thread::sleep(1000, false);
}
};
and then that'll cause the thread executing the 'test' runnable to sleep 1000 milliseonds?
It will put to sleep whichever thread calls this member function.
No, this will put the original thread to sleep, not the one you start.
Yes it will -- provided that it's called from that thread (i.e. from within thread::run()
).
Due to this, I'd recommend making sleep()
a protected member function.
Or, as an alternative, make it a static method, with semantics of thread::sleep()
being a service that pauses calling thread (this approach is used, e.g., in Java standard library).
It is not possible to make an other than calling thread sleep, because the thread can be in the middle of something at that moment.
If you need to suspend newly created thread, you should use SuspendThread
instead or pass CREATE_SUSPENDED
to _beginthreadex()
, but this can cause deadlocks in some cases
see http://msdn.microsoft.com/en-us/library/ms686345%28v=VS.85%29.aspx
精彩评论