1 /* -----------------------------------------------------------------------------
2 * $Id: Select.c,v 1.23 2003/01/25 15:54:50 wolfgang Exp $
4 * (c) The GHC Team 1995-2002
6 * Support for concurrent non-blocking I/O and thread waiting.
8 * ---------------------------------------------------------------------------*/
10 /* we're outside the realms of POSIX here... */
11 /* #include "PosixSource.h" */
19 #include "Capability.h"
21 # ifdef HAVE_SYS_TYPES_H
22 # include <sys/types.h>
25 # ifdef HAVE_SYS_TIME_H
26 # include <sys/time.h>
29 # ifdef mingw32_TARGET_OS
39 #ifdef RTS_SUPPORTS_THREADS
40 static rtsBool isWorkerBlockedInAwaitEvent = rtsFalse;
41 static rtsBool workerWakeupPending = rtsFalse;
42 #ifndef mingw32_TARGET_OS
43 static int workerWakeupPipe[2];
44 static rtsBool workerWakeupInited = rtsFalse;
48 /* There's a clever trick here to avoid problems when the time wraps
49 * around. Since our maximum delay is smaller than 31 bits of ticks
50 * (it's actually 31 bits of microseconds), we can safely check
51 * whether a timer has expired even if our timer will wrap around
52 * before the target is reached, using the following formula:
54 * (int)((uint)current_time - (uint)target_time) < 0
56 * if this is true, then our time has expired.
57 * (idea due to Andy Gill).
60 wakeUpSleepingThreads(nat ticks)
63 rtsBool flag = rtsFalse;
65 while (sleeping_queue != END_TSO_QUEUE &&
66 (int)(ticks - sleeping_queue->block_info.target) > 0) {
68 sleeping_queue = tso->link;
69 tso->why_blocked = NotBlocked;
70 tso->link = END_TSO_QUEUE;
71 IF_DEBUG(scheduler,belch("Waking up sleeping thread %d\n", tso->id));
72 PUSH_ON_RUN_QUEUE(tso);
78 /* Argument 'wait' says whether to wait for I/O to become available,
79 * or whether to just check and return immediately. If there are
80 * other threads ready to run, we normally do the non-waiting variety,
81 * otherwise we wait (see Schedule.c).
83 * SMP note: must be called with sched_mutex locked.
85 * Windows: select only works on sockets, so this doesn't really work,
86 * though it makes things better than before. MsgWaitForMultipleObjects
87 * should really be used, though it only seems to work for read handles,
92 awaitEvent(rtsBool wait)
94 StgTSO *tso, *prev, *next;
97 #ifndef mingw32_TARGET_OS
101 rtsBool select_succeeded = rtsTrue;
102 rtsBool unblock_all = rtsFalse;
110 belch("scheduler: checking for threads blocked on I/O");
117 /* loop until we've woken up some threads. This loop is needed
118 * because the select timing isn't accurate, we sometimes sleep
119 * for a while but not long enough to wake up a thread in
124 ticks = timestamp = getourtimeofday();
125 if (wakeUpSleepingThreads(ticks)) {
131 } else if (sleeping_queue != END_TSO_QUEUE) {
132 min = (sleeping_queue->block_info.target - ticks)
133 * TICK_MILLISECS * 1000;
138 #ifndef mingw32_TARGET_OS
140 * Collect all of the fd's that we're interested in
145 for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
148 switch (tso->why_blocked) {
151 int fd = tso->block_info.fd;
152 maxfd = (fd > maxfd) ? fd : maxfd;
159 int fd = tso->block_info.fd;
160 maxfd = (fd > maxfd) ? fd : maxfd;
170 #ifdef RTS_SUPPORTS_THREADS
171 if(!workerWakeupInited) {
172 pipe(workerWakeupPipe);
173 workerWakeupInited = rtsTrue;
175 FD_SET(workerWakeupPipe[0], &rfd);
176 maxfd = workerWakeupPipe[0] > maxfd ? workerWakeupPipe[0] : maxfd;
179 /* Release the scheduler lock while we do the poll.
180 * this means that someone might muck with the blocked_queue
181 * while we do this, but it shouldn't matter:
183 * - another task might poll for I/O and remove one
184 * or more threads from the blocked_queue.
185 * - more I/O threads may be added to blocked_queue.
186 * - more delayed threads may be added to blocked_queue. We'll
187 * just subtract delta from their delays after the poll.
189 * I believe none of these cases lead to trouble --SDM.
192 #ifdef RTS_SUPPORTS_THREADS
193 isWorkerBlockedInAwaitEvent = rtsTrue;
194 workerWakeupPending = rtsFalse;
196 RELEASE_LOCK(&sched_mutex);
198 /* Check for any interesting events */
200 tv.tv_sec = min / 1000000;
201 tv.tv_usec = min % 1000000;
203 while ((numFound = select(maxfd+1, &rfd, &wfd, NULL, &tv)) < 0) {
204 if (errno != EINTR) {
205 /* Handle bad file descriptors by unblocking all the
206 waiting threads. Why? Because a thread might have been
207 a bit naughty and closed a file descriptor while another
208 was blocked waiting. This is less-than-good programming
209 practice, but having the RTS as a result fall over isn't
210 acceptable, so we simply unblock all the waiting threads
211 should we see a bad file descriptor & give the threads
212 a chance to clean up their act.
214 Note: assume here that threads becoming unblocked
215 will try to read/write the file descriptor before trying
216 to issue a threadWaitRead/threadWaitWrite again (==> an
217 IOError will result for the thread that's got the bad
218 file descriptor.) Hence, there's no danger of a bad
219 file descriptor being repeatedly select()'ed on, so
222 if ( errno == EBADF ) {
223 unblock_all = rtsTrue;
226 fprintf(stderr,"%d\n", errno);
229 barf("select failed");
232 #else /* on mingwin */
233 #ifdef RTS_SUPPORTS_THREADS
234 isWorkerBlockedInAwaitEvent = rtsTrue;
236 RELEASE_LOCK(&sched_mutex);
238 Sleep(0); /* don't busy wait */
239 #endif /* mingw32_TARGET_OS */
240 ACQUIRE_LOCK(&sched_mutex);
241 #ifdef RTS_SUPPORTS_THREADS
242 isWorkerBlockedInAwaitEvent = rtsFalse;
245 #ifndef mingw32_TARGET_OS
246 /* We got a signal; could be one of ours. If so, we need
247 * to start up the signal handler straight away, otherwise
248 * we could block for a long time before the signal is
251 if (signals_pending()) {
252 RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
253 startSignalHandlers();
254 ACQUIRE_LOCK(&sched_mutex);
255 return; /* still hold the lock */
259 /* we were interrupted, return to the scheduler immediately.
262 return; /* still hold the lock */
265 /* check for threads that need waking up
267 wakeUpSleepingThreads(getourtimeofday());
269 /* If new runnable threads have arrived, stop waiting for
272 if (run_queue_hd != END_TSO_QUEUE) {
273 return; /* still hold the lock */
276 #ifdef RTS_SUPPORTS_THREADS
277 /* If another worker thread wants to take over,
278 * return to the scheduler
280 if (needToYieldToReturningWorker()) {
281 return; /* still hold the lock */
285 #ifdef RTS_SUPPORTS_THREADS
286 isWorkerBlockedInAwaitEvent = rtsTrue;
288 RELEASE_LOCK(&sched_mutex);
291 ACQUIRE_LOCK(&sched_mutex);
293 /* Step through the waiting queue, unblocking every thread that now has
294 * a file descriptor in a ready state.
298 if (select_succeeded || unblock_all) {
299 for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
301 switch (tso->why_blocked) {
303 ready = unblock_all || FD_ISSET(tso->block_info.fd, &rfd);
306 ready = unblock_all || FD_ISSET(tso->block_info.fd, &wfd);
313 IF_DEBUG(scheduler,belch("Waking up blocked thread %d\n", tso->id));
314 tso->why_blocked = NotBlocked;
315 tso->link = END_TSO_QUEUE;
316 PUSH_ON_RUN_QUEUE(tso);
319 blocked_queue_hd = tso;
327 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
329 prev->link = END_TSO_QUEUE;
330 blocked_queue_tl = prev;
334 #if defined(RTS_SUPPORTS_THREADS) && !defined(mingw32_TARGET_OS)
335 // if we were woken up by wakeBlockedWorkerThread,
336 // read the dummy byte from the pipe
337 if(select_succeeded && FD_ISSET(workerWakeupPipe[0], &rfd)) {
340 read(workerWakeupPipe[0],&dummy,1);
343 } while (wait && !interrupted && run_queue_hd == END_TSO_QUEUE);
347 #ifdef RTS_SUPPORTS_THREADS
348 /* wakeBlockedWorkerThread
350 * If a worker thread is currently blocked within awaitEvent,
352 * Must be called with sched_mutex held.
356 wakeBlockedWorkerThread()
358 #ifndef mingw32_TARGET_OS
359 if(isWorkerBlockedInAwaitEvent && !workerWakeupPending) {
360 unsigned char dummy = 42; // Any value will do here
362 // write something so that select() wakes up
363 write(workerWakeupPipe[1],&dummy,1);
364 workerWakeupPending = rtsTrue;
367 // The Win32 implementation currently uses a polling loop,
368 // so there is no need to explicitly wake it