Add API and ABI stability guidance to the C language docs
[pgsql.git] / src / port / pgsleep.c
blob1284458bfce3a635af693dfeff16f4748ca8a16a
1 /*-------------------------------------------------------------------------
3 * pgsleep.c
4 * Portable delay handling.
7 * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
9 * src/port/pgsleep.c
11 *-------------------------------------------------------------------------
13 #include "c.h"
15 #include <time.h>
18 * In a Windows backend, we don't use this implementation, but rather
19 * the signal-aware version in src/backend/port/win32/signal.c.
21 #if defined(FRONTEND) || !defined(WIN32)
24 * pg_usleep --- delay the specified number of microseconds.
26 * NOTE: Although the delay is specified in microseconds, older Unixen and
27 * Windows use periodic kernel ticks to wake up, which might increase the delay
28 * time significantly. We've observed delay increases as large as 20
29 * milliseconds on supported platforms.
31 * On machines where "long" is 32 bits, the maximum delay is ~2000 seconds.
33 * CAUTION: It's not a good idea to use long sleeps in the backend. They will
34 * silently return early if a signal is caught, but that doesn't include
35 * latches being set on most OSes, and even signal handlers that set MyLatch
36 * might happen to run before the sleep begins, allowing the full delay.
37 * Better practice is to use WaitLatch() with a timeout, so that backends
38 * respond to latches and signals promptly.
40 void
41 pg_usleep(long microsec)
43 if (microsec > 0)
45 #ifndef WIN32
46 struct timespec delay;
48 delay.tv_sec = microsec / 1000000L;
49 delay.tv_nsec = (microsec % 1000000L) * 1000;
50 (void) nanosleep(&delay, NULL);
51 #else
52 SleepEx((microsec < 500 ? 1 : (microsec + 500) / 1000), FALSE);
53 #endif
57 #endif /* defined(FRONTEND) || !defined(WIN32) */