- Sleep function (synchapi.h)
- Syntax
- Parameters
- Return value
- Remarks
- Thread. Sleep Метод
- Определение
- Перегрузки
- Sleep(Int32)
- Параметры
- Исключения
- Примеры
- Комментарии
- CPP WINDOWS : is there a sleep function in microseconds?
- 4 Answers 4
- Not the answer you’re looking for? Browse other questions tagged c++ windows sleep or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- How do you make a program sleep in C++ on Win 32?
- 7 Answers 7
- Putting PC into sleep mode programmatically
Sleep function (synchapi.h)
Suspends the execution of the current thread until the time-out interval elapses.
To enter an alertable wait state, use the SleepEx function.
Syntax
Parameters
The time interval for which execution is to be suspended, in milliseconds.
A value of zero causes the thread to relinquish the remainder of its time slice to any other thread that is ready to run. If there are no other threads ready to run, the function returns immediately, and the thread continues execution.WindowsВ XP:В В A value of zero causes the thread to relinquish the remainder of its time slice to any other thread of equal priority that is ready to run. If there are no other threads of equal priority ready to run, the function returns immediately, and the thread continues execution. This behavior changed starting with Windows ServerВ 2003.
A value of INFINITE indicates that the suspension should not time out.
Return value
Remarks
This function causes a thread to relinquish the remainder of its time slice and become unrunnable for an interval based on the value of dwMilliseconds. The system clock «ticks» at a constant rate. If dwMilliseconds is less than the resolution of the system clock, the thread may sleep for less than the specified length of time. If dwMilliseconds is greater than one tick but less than two, the wait can be anywhere between one and two ticks, and so on. To increase the accuracy of the sleep interval, call the timeGetDevCaps function to determine the supported minimum timer resolution and the timeBeginPeriod function to set the timer resolution to its minimum. Use caution when calling timeBeginPeriod, as frequent calls can significantly affect the system clock, system power usage, and the scheduler. If you call timeBeginPeriod, call it one time early in the application and be sure to call the timeEndPeriod function at the very end of the application.
After the sleep interval has passed, the thread is ready to run. If you specify 0 milliseconds, the thread will relinquish the remainder of its time slice but remain ready. Note that a ready thread is not guaranteed to run immediately. Consequently, the thread may not run until some time after the sleep interval elapses. For more information, see Scheduling Priorities.
Be careful when using Sleep in the following scenarios:
- Code that directly or indirectly creates windows (for example, DDE and COM CoInitialize). If a thread creates any windows, it must process messages. Message broadcasts are sent to all windows in the system. If you have a thread that uses Sleep with infinite delay, the system will deadlock.
- Threads that are under concurrency control. For example, an I/O completion port or thread pool limits the number of associated threads that can run. If the maximum number of threads is already running, no additional associated thread can run until a running thread finishes. If a thread uses Sleep with an interval of zero to wait for one of the additional associated threads to accomplish some work, the process might deadlock.
For these scenarios, use MsgWaitForMultipleObjects or MsgWaitForMultipleObjectsEx, rather than Sleep.
Windows Phone 8.1: This function is supported for Windows Phone Store apps on Windows Phone 8.1 and later.
WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.
Thread. Sleep Метод
Определение
Приостанавливает текущий поток на заданное время. Suspends the current thread for the specified amount of time.
Перегрузки
Приостанавливает текущий поток на заданное количество миллисекунд. Suspends the current thread for the specified number of milliseconds.
Приостанавливает текущий поток на заданное время. Suspends the current thread for the specified amount of time.
Sleep(Int32)
Приостанавливает текущий поток на заданное количество миллисекунд. Suspends the current thread for the specified number of milliseconds.
Параметры
Количество миллисекунд, на которое приостанавливается поток. The number of milliseconds for which the thread is suspended. Если значение аргумента millisecondsTimeout равно нулю, поток освобождает оставшуюся часть своего интервала времени для любого потока с таким же приоритетом, готовым к выполнению. If the value of the millisecondsTimeout argument is zero, the thread relinquishes the remainder of its time slice to any thread of equal priority that is ready to run. Если других готовых к выполнению потоков с таким же приоритетом нет, выполнение текущего потока не приостанавливается. If there are no other threads of equal priority that are ready to run, execution of the current thread is not suspended.
Исключения
Значение времени ожидания является отрицательной величиной и не равно Infinite. The time-out value is negative and is not equal to Infinite.
Примеры
В следующем примере метод используется Sleep для блокировки основного потока приложения. The following example uses the Sleep method to block the application’s main thread.
Комментарии
Выполнение потока не будет запланировано операционной системой на указанный период времени. The thread will not be scheduled for execution by the operating system for the amount of time specified. Этот метод изменяет состояние потока для включения WaitSleepJoin . This method changes the state of the thread to include WaitSleepJoin.
Можно указать Timeout.Infinite для параметра, millisecondsTimeout чтобы приостановить поток в течение неограниченного времени. You can specify Timeout.Infinite for the millisecondsTimeout parameter to suspend the thread indefinitely. Однако System.Threading Mutex Monitor EventWaitHandle Semaphore для синхронизации потоков или управления ресурсами рекомендуется использовать другие классы, такие как,, или. However, we recommend that you use other System.Threading classes such as Mutex, Monitor, EventWaitHandle, or Semaphore instead to synchronize threads or manage resources.
Системные тактовые импульсы с заданной скоростью, называемой разрешением часов. The system clock ticks at a specific rate called the clock resolution. Фактическое время ожидания может быть не равно указанному времени ожидания, так как указанное время ожидания будет изменено в соответствии с тактами времени. The actual timeout might not be exactly the specified timeout, because the specified timeout will be adjusted to coincide with clock ticks. Дополнительные сведения о разрешении часов и времени ожидания см. в разделе Функция Sleep из системных API Windows. For more information on clock resolution and the waiting time, see the Sleep function from the Windows system APIs.
Этот метод не выполняет стандартные конвейеры COM и SendMessage. This method does not perform standard COM and SendMessage pumping.
Если необходимо включить спящий режим в потоке, который имеет STAThreadAttribute , но вы хотите выполнить стандартные выгрузки com и SendMessage, рассмотрите возможность использования одной из перегруженных версий Join метода, указывающих интервал времени ожидания. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.
CPP WINDOWS : is there a sleep function in microseconds?
I know there is for milliseconds (Sleep(milli))
but I couldn’t find one for micro..
4 Answers 4
The VS 11 dev preview includes the part of the standard library dealing with threads. So now you can say:
Of course this doesn’t mean the thread will wake up after exactly this amount of time, but it should be as close as the platform (and library implementation) allows for. As other comments have pointed out, Windows doesn’t actually allow threads to sleep for durations this short.
You can use rdtsc instruction or QueryPerformanceCounter Windows API function to get high-resolution counters. You can calibrate them then with GetTickCount , or time functions for example.
Windows can’t sleep for less than a millisecond. Time slices tend to be much higher than 1ms, so it isn’t really possible even with a thread a highest priority.
If you don’t care about burning CPU, you can spin until QueryPerformanceCounter has elapsed your time.
I just wrote a detailed comment about the sleep() function and spinning the performance counter. To avoid typing it here again, here is the link:
Not the answer you’re looking for? Browse other questions tagged c++ windows sleep or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How do you make a program sleep in C++ on Win 32?
How does one «pause» a program in C++ on Win 32, and what libraries must be included?
7 Answers 7
Or if you want to pause your program while waiting for another program, use WaitForSingleObject.
In C++11, you can do this with standard library facilities:
If you are using boost, you can use the thread::sleep function:
Otherwise, you are going to have to use the win32 api:
And, apparently, C++0x includes this:
If you wish for the program to stay responsive while «paused», you need to use a timer event.
Please note that the code above was tested on Code::Blocks 12.11 and Visual Studio 2012
on Windows 7.
For forcing your programme stop or wait, you have several options :
- sleep(unsigned int)
The value has to be a positive integer in millisecond. That means that if you want your programme wait for 2 second, enter 2000.
Here’s an example :
If you wait too long, that probably means the parameter is in second. So change it like that :
For those who get error message or problem using sleep try to replace it by _sleep or Sleep especially on Code::Bloks.
And if you still getting probleme, try to add of one this library on the biggining of the code.
A simple «Hello world» programme on windows console application would probably close before you can see anything. That the case where you can use system(«Pause»).
If you get the message «error: ‘system’ was not declared in this scope» just add the following line at the biggining of the code :
The same result can be reached by using cin.ignore() :
Just don’t forget to add the library conio.h :
You can have message telling you to use _getch() insted of getch
Putting PC into sleep mode programmatically
An old problem, maybe (?) resolved for older Windows version, but not for Windows 10!
The solutions proposed in old discussions (. SetSuspendState with parameters 0,1,0 (or Sleep), with or without prior hibernate off . ) dont work on Windows 10 systems; at least not on all: the initiated mode is mostly hibernate, not sleep.
What I found out: In older Windows versions there was something like this in the Registry: [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\sleep\command] @=»rundll32.exe powrprof.dll,SetSuspendState Sleep» This obviously was the sleep command. At least on my Windows 10 PCs there is no such entry!
Somebody here with new answers?
================== EDITED: After this my OP I discovered that this is not a Windows 10 issue, it is a Surface 3 issue, related to the power option used on Surface 3 as Sleep mode:
The Sleep mode used by Surface 3 seems to be «Modern Standby» = «S0 Low Power Idle» = «Connected Network Standby». (Not the usual S3 Sleep mode. )
The commands using SetSuspendState seems to be unable at all to initiate the Sleep mode on a Surface 3.
A new wording for my question: All what I would like to have is a command which does the same as the Power button on a Surface 3 which is set to «power-button action = Sleep», or as the Sleep button on an external (USB) keyboard when Surface 3 is set to «sleep-button action = Sleep».