BDev338
BDev338

Reputation: 19

[C++]Would this be a valid approach for a 'sleep' function in a thread?

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):

#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?

Upvotes: 1

Views: 509

Answers (4)

imaximchuk
imaximchuk

Reputation: 748

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

Upvotes: 0

sbi
sbi

Reputation: 224139

It will put to sleep whichever thread calls this member function.

Upvotes: 2

atzz
atzz

Reputation: 18010

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.

Upvotes: 0

sharptooth
sharptooth

Reputation: 170509

No, this will put the original thread to sleep, not the one you start.

Upvotes: 1

Related Questions