How to let a Thread sleep for a period of time


Hi,

How to let a Thread sleep for a period of time using c or c++ ?
For Windows, you can use "SuspendThread()","ResumeThread()" and "Sleep" (using Windows API with the windows.h header).
e.g.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<windows.h>
#include<iostream>
DWORD WINAPI thread(LPVOID arg)
{
    Sleep(3000);
    std::cout<<"thread finalized";
    return 0;
}
int main(void)
{
    std::cout<<"threads...\n";
    CreateThread(NULL,0,thread,NULL,0,NULL);
    system("pause >nul");
    return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<windows.h>
#include<iostream>
DWORD WINAPI thread(LPVOID arg)
{
    int i;
    for(i = 0; i <= 200; i++) std::cout<<"outpt "<<i<<"...\n";
    return 0;
}
int main(void)
{
    HANDLE h_thread;
    h_thread = CreateThread(NULL,0,thread,NULL,0,NULL);
    SuspendThread(h_thread);
    Sleep(1000);
    ResumeThread(h_thread);
    Sleep(20);    
    SuspendThread(h_thread);
    Sleep(1000);
    ResumeThread(h_thread);
    SuspendThread(h_thread);
    Sleep(1000);
    ResumeThread(h_thread);
    Sleep(20);    
    SuspendThread(h_thread);
    Sleep(1000);
    ResumeThread(h_thread);
    system("pause >nul");
    return 0;
}

I hope this help...
wn_br
Or, if You only want the thread to pass execution to another thread (not a specific one), you could do

1
2
while(/*condition blabla*/)
SwitchToThread();

Thanks. Its working...
Topic archived. No new replies allowed.