1 /* -----------------------------------------------------------------------------
2 * $Id: Select.c,v 1.26 2003/02/22 06:13:41 sof 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" */
15 #ifndef mingw32_TARGET_OS
24 #include "Capability.h"
26 # ifdef HAVE_SYS_TYPES_H
27 # include <sys/types.h>
30 # ifdef HAVE_SYS_TIME_H
31 # include <sys/time.h>
40 #ifdef RTS_SUPPORTS_THREADS
41 static rtsBool isWorkerBlockedInAwaitEvent = rtsFalse;
42 static rtsBool workerWakeupPending = rtsFalse;
43 static int workerWakeupPipe[2];
44 static rtsBool workerWakeupInited = rtsFalse;
47 /* There's a clever trick here to avoid problems when the time wraps
48 * around. Since our maximum delay is smaller than 31 bits of ticks
49 * (it's actually 31 bits of microseconds), we can safely check
50 * whether a timer has expired even if our timer will wrap around
51 * before the target is reached, using the following formula:
53 * (int)((uint)current_time - (uint)target_time) < 0
55 * if this is true, then our time has expired.
56 * (idea due to Andy Gill).
59 wakeUpSleepingThreads(nat ticks)
62 rtsBool flag = rtsFalse;
64 while (sleeping_queue != END_TSO_QUEUE &&
65 (int)(ticks - sleeping_queue->block_info.target) > 0) {
67 sleeping_queue = tso->link;
68 tso->why_blocked = NotBlocked;
69 tso->link = END_TSO_QUEUE;
70 IF_DEBUG(scheduler,belch("Waking up sleeping thread %d\n", tso->id));
71 PUSH_ON_RUN_QUEUE(tso);
77 /* Argument 'wait' says whether to wait for I/O to become available,
78 * or whether to just check and return immediately. If there are
79 * other threads ready to run, we normally do the non-waiting variety,
80 * otherwise we wait (see Schedule.c).
82 * SMP note: must be called with sched_mutex locked.
84 * Windows: select only works on sockets, so this doesn't really work,
85 * though it makes things better than before. MsgWaitForMultipleObjects
86 * should really be used, though it only seems to work for read handles,
91 awaitEvent(rtsBool wait)
93 StgTSO *tso, *prev, *next;
98 rtsBool select_succeeded = rtsTrue;
99 rtsBool unblock_all = rtsFalse;
107 belch("scheduler: checking for threads blocked on I/O");
114 /* loop until we've woken up some threads. This loop is needed
115 * because the select timing isn't accurate, we sometimes sleep
116 * for a while but not long enough to wake up a thread in
121 ticks = timestamp = getourtimeofday();
122 if (wakeUpSleepingThreads(ticks)) {
128 } else if (sleeping_queue != END_TSO_QUEUE) {
129 min = (sleeping_queue->block_info.target - ticks)
130 * TICK_MILLISECS * 1000;
136 * Collect all of the fd's that we're interested in
141 for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
144 switch (tso->why_blocked) {
147 int fd = tso->block_info.fd;
148 maxfd = (fd > maxfd) ? fd : maxfd;
155 int fd = tso->block_info.fd;
156 maxfd = (fd > maxfd) ? fd : maxfd;
166 #ifdef RTS_SUPPORTS_THREADS
167 if(!workerWakeupInited) {
168 pipe(workerWakeupPipe);
169 workerWakeupInited = rtsTrue;
171 FD_SET(workerWakeupPipe[0], &rfd);
172 maxfd = workerWakeupPipe[0] > maxfd ? workerWakeupPipe[0] : maxfd;
175 /* Release the scheduler lock while we do the poll.
176 * this means that someone might muck with the blocked_queue
177 * while we do this, but it shouldn't matter:
179 * - another task might poll for I/O and remove one
180 * or more threads from the blocked_queue.
181 * - more I/O threads may be added to blocked_queue.
182 * - more delayed threads may be added to blocked_queue. We'll
183 * just subtract delta from their delays after the poll.
185 * I believe none of these cases lead to trouble --SDM.
188 #ifdef RTS_SUPPORTS_THREADS
189 isWorkerBlockedInAwaitEvent = rtsTrue;
190 workerWakeupPending = rtsFalse;
192 RELEASE_LOCK(&sched_mutex);
194 /* Check for any interesting events */
196 tv.tv_sec = min / 1000000;
197 tv.tv_usec = min % 1000000;
199 while ((numFound = select(maxfd+1, &rfd, &wfd, NULL, &tv)) < 0) {
200 if (errno != EINTR) {
201 /* Handle bad file descriptors by unblocking all the
202 waiting threads. Why? Because a thread might have been
203 a bit naughty and closed a file descriptor while another
204 was blocked waiting. This is less-than-good programming
205 practice, but having the RTS as a result fall over isn't
206 acceptable, so we simply unblock all the waiting threads
207 should we see a bad file descriptor & give the threads
208 a chance to clean up their act.
210 Note: assume here that threads becoming unblocked
211 will try to read/write the file descriptor before trying
212 to issue a threadWaitRead/threadWaitWrite again (==> an
213 IOError will result for the thread that's got the bad
214 file descriptor.) Hence, there's no danger of a bad
215 file descriptor being repeatedly select()'ed on, so
218 if ( errno == EBADF ) {
219 unblock_all = rtsTrue;
222 fprintf(stderr,"%d\n", errno);
225 barf("select failed");
228 ACQUIRE_LOCK(&sched_mutex);
229 #ifdef RTS_SUPPORTS_THREADS
230 isWorkerBlockedInAwaitEvent = rtsFalse;
233 /* We got a signal; could be one of ours. If so, we need
234 * to start up the signal handler straight away, otherwise
235 * we could block for a long time before the signal is
238 if (signals_pending()) {
239 RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
240 startSignalHandlers();
241 ACQUIRE_LOCK(&sched_mutex);
242 return; /* still hold the lock */
245 /* we were interrupted, return to the scheduler immediately.
248 return; /* still hold the lock */
251 /* check for threads that need waking up
253 wakeUpSleepingThreads(getourtimeofday());
255 /* If new runnable threads have arrived, stop waiting for
258 if (run_queue_hd != END_TSO_QUEUE) {
259 return; /* still hold the lock */
262 #ifdef RTS_SUPPORTS_THREADS
263 /* If another worker thread wants to take over,
264 * return to the scheduler
266 if (needToYieldToReturningWorker()) {
267 return; /* still hold the lock */
271 #ifdef RTS_SUPPORTS_THREADS
272 isWorkerBlockedInAwaitEvent = rtsTrue;
274 RELEASE_LOCK(&sched_mutex);
277 ACQUIRE_LOCK(&sched_mutex);
279 /* Step through the waiting queue, unblocking every thread that now has
280 * a file descriptor in a ready state.
284 if (select_succeeded || unblock_all) {
285 for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
287 switch (tso->why_blocked) {
289 ready = unblock_all || FD_ISSET(tso->block_info.fd, &rfd);
292 ready = unblock_all || FD_ISSET(tso->block_info.fd, &wfd);
299 IF_DEBUG(scheduler,belch("Waking up blocked thread %d\n", tso->id));
300 tso->why_blocked = NotBlocked;
301 tso->link = END_TSO_QUEUE;
302 PUSH_ON_RUN_QUEUE(tso);
305 blocked_queue_hd = tso;
313 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
315 prev->link = END_TSO_QUEUE;
316 blocked_queue_tl = prev;
320 #if defined(RTS_SUPPORTS_THREADS)
321 // if we were woken up by wakeBlockedWorkerThread,
322 // read the dummy byte from the pipe
323 if(select_succeeded && FD_ISSET(workerWakeupPipe[0], &rfd)) {
326 read(workerWakeupPipe[0],&dummy,1);
329 } while (wait && !interrupted && run_queue_hd == END_TSO_QUEUE);
333 #ifdef RTS_SUPPORTS_THREADS
334 /* wakeBlockedWorkerThread
336 * If a worker thread is currently blocked within awaitEvent,
338 * Must be called with sched_mutex held.
341 wakeBlockedWorkerThread()
343 if(isWorkerBlockedInAwaitEvent && !workerWakeupPending) {
344 unsigned char dummy = 42; // Any value will do here
346 // write something so that select() wakes up
347 write(workerWakeupPipe[1],&dummy,1);
348 workerWakeupPending = rtsTrue;
353 #endif /* !mingw_TARGET_OS */