1 /* -----------------------------------------------------------------------------
2 * $Id: Select.c,v 1.33 2004/09/03 15:28:53 simonmar Exp $
4 * (c) The GHC Team 1995-2002
6 * Support for concurrent non-blocking I/O and thread waiting.
8 * ---------------------------------------------------------------------------*/
11 /* we're outside the realms of POSIX here... */
12 /* #include "PosixSource.h" */
21 #include "Capability.h"
23 # ifdef HAVE_SYS_TYPES_H
24 # include <sys/types.h>
27 # ifdef HAVE_SYS_TIME_H
28 # include <sys/time.h>
41 #ifdef RTS_SUPPORTS_THREADS
42 static rtsBool isWorkerBlockedInAwaitEvent = rtsFalse;
43 static rtsBool workerWakeupPending = rtsFalse;
44 static int workerWakeupPipe[2];
45 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,debugBelch("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;
99 rtsBool select_succeeded = rtsTrue;
100 rtsBool unblock_all = rtsFalse;
108 debugBelch("scheduler: checking for threads blocked on I/O");
110 debugBelch(" (waiting)");
115 /* loop until we've woken up some threads. This loop is needed
116 * because the select timing isn't accurate, we sometimes sleep
117 * for a while but not long enough to wake up a thread in
122 ticks = timestamp = getourtimeofday();
123 if (wakeUpSleepingThreads(ticks)) {
129 } else if (sleeping_queue != END_TSO_QUEUE) {
130 min = (sleeping_queue->block_info.target - ticks)
131 * TICK_MILLISECS * 1000;
137 * Collect all of the fd's that we're interested in
142 for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
145 switch (tso->why_blocked) {
148 int fd = tso->block_info.fd;
149 maxfd = (fd > maxfd) ? fd : maxfd;
156 int fd = tso->block_info.fd;
157 maxfd = (fd > maxfd) ? fd : maxfd;
167 #ifdef RTS_SUPPORTS_THREADS
168 if(!workerWakeupInited) {
169 pipe(workerWakeupPipe);
170 workerWakeupInited = rtsTrue;
172 FD_SET(workerWakeupPipe[0], &rfd);
173 maxfd = workerWakeupPipe[0] > maxfd ? workerWakeupPipe[0] : maxfd;
176 /* Release the scheduler lock while we do the poll.
177 * this means that someone might muck with the blocked_queue
178 * while we do this, but it shouldn't matter:
180 * - another task might poll for I/O and remove one
181 * or more threads from the blocked_queue.
182 * - more I/O threads may be added to blocked_queue.
183 * - more delayed threads may be added to blocked_queue. We'll
184 * just subtract delta from their delays after the poll.
186 * I believe none of these cases lead to trouble --SDM.
189 #ifdef RTS_SUPPORTS_THREADS
190 isWorkerBlockedInAwaitEvent = rtsTrue;
191 workerWakeupPending = rtsFalse;
193 RELEASE_LOCK(&sched_mutex);
195 /* Check for any interesting events */
197 tv.tv_sec = min / 1000000;
198 tv.tv_usec = min % 1000000;
200 while ((numFound = select(maxfd+1, &rfd, &wfd, NULL, &tv)) < 0) {
201 if (errno != EINTR) {
202 /* Handle bad file descriptors by unblocking all the
203 waiting threads. Why? Because a thread might have been
204 a bit naughty and closed a file descriptor while another
205 was blocked waiting. This is less-than-good programming
206 practice, but having the RTS as a result fall over isn't
207 acceptable, so we simply unblock all the waiting threads
208 should we see a bad file descriptor & give the threads
209 a chance to clean up their act.
211 Note: assume here that threads becoming unblocked
212 will try to read/write the file descriptor before trying
213 to issue a threadWaitRead/threadWaitWrite again (==> an
214 IOError will result for the thread that's got the bad
215 file descriptor.) Hence, there's no danger of a bad
216 file descriptor being repeatedly select()'ed on, so
219 if ( errno == EBADF ) {
220 unblock_all = rtsTrue;
224 barf("select failed");
227 ACQUIRE_LOCK(&sched_mutex);
228 #ifdef RTS_SUPPORTS_THREADS
229 isWorkerBlockedInAwaitEvent = rtsFalse;
232 /* We got a signal; could be one of ours. If so, we need
233 * to start up the signal handler straight away, otherwise
234 * we could block for a long time before the signal is
237 #if defined(RTS_USER_SIGNALS)
238 if (signals_pending()) {
239 RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
240 startSignalHandlers();
241 ACQUIRE_LOCK(&sched_mutex);
242 return; /* still hold the lock */
246 /* we were interrupted, return to the scheduler immediately.
249 return; /* still hold the lock */
252 /* check for threads that need waking up
254 wakeUpSleepingThreads(getourtimeofday());
256 /* If new runnable threads have arrived, stop waiting for
259 if (run_queue_hd != END_TSO_QUEUE) {
260 return; /* still hold the lock */
263 #ifdef RTS_SUPPORTS_THREADS
264 /* If another worker thread wants to take over,
265 * return to the scheduler
267 if (needToYieldToReturningWorker()) {
268 return; /* still hold the lock */
272 #ifdef RTS_SUPPORTS_THREADS
273 isWorkerBlockedInAwaitEvent = rtsTrue;
275 RELEASE_LOCK(&sched_mutex);
278 ACQUIRE_LOCK(&sched_mutex);
280 /* Step through the waiting queue, unblocking every thread that now has
281 * a file descriptor in a ready state.
285 if (select_succeeded || unblock_all) {
286 for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
288 switch (tso->why_blocked) {
290 ready = unblock_all || FD_ISSET(tso->block_info.fd, &rfd);
293 ready = unblock_all || FD_ISSET(tso->block_info.fd, &wfd);
300 IF_DEBUG(scheduler,debugBelch("Waking up blocked thread %d\n", tso->id));
301 tso->why_blocked = NotBlocked;
302 tso->link = END_TSO_QUEUE;
303 PUSH_ON_RUN_QUEUE(tso);
306 blocked_queue_hd = tso;
314 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
316 prev->link = END_TSO_QUEUE;
317 blocked_queue_tl = prev;
321 #if defined(RTS_SUPPORTS_THREADS)
322 // if we were woken up by wakeBlockedWorkerThread,
323 // read the dummy byte from the pipe
324 if(select_succeeded && FD_ISSET(workerWakeupPipe[0], &rfd)) {
327 read(workerWakeupPipe[0],&dummy,1);
330 } while (wait && !interrupted && run_queue_hd == END_TSO_QUEUE);
334 #ifdef RTS_SUPPORTS_THREADS
335 /* wakeBlockedWorkerThread
337 * If a worker thread is currently blocked within awaitEvent,
339 * Must be called with sched_mutex held.
342 wakeBlockedWorkerThread()
344 if(isWorkerBlockedInAwaitEvent && !workerWakeupPending) {
345 unsigned char dummy = 42; // Any value will do here
347 // write something so that select() wakes up
348 write(workerWakeupPipe[1],&dummy,1);
349 workerWakeupPending = rtsTrue;
353 /* resetWorkerWakeupPipeAfterFork
355 * To be called right after a fork().
356 * After the fork(), the worker wakeup pipe will be shared
357 * with the parent process, and that's something we don't want.
360 resetWorkerWakeupPipeAfterFork()
362 if(workerWakeupInited) {
363 close(workerWakeupPipe[0]);
364 close(workerWakeupPipe[1]);
366 workerWakeupInited = rtsFalse;