+ } else {
+ grabCapability(pCap);
+ }
+ return;
+}
+
+
+/* -----------------------------------------------------------------------------
+ Yielding/waiting for capabilities
+ -------------------------------------------------------------------------- */
+
+/*
+ * Function: yieldToReturningWorker(Mutex*,Capability*,Condition*)
+ *
+ * Purpose: when, upon entry to the Scheduler, an OS worker thread
+ * spots that one or more threads are blocked waiting for
+ * permission to return back their result, it gives up
+ * its Capability.
+ * Immediately afterwards, it tries to reaquire the Capabilty
+ * using waitForWorkCapability.
+ *
+ *
+ * Pre-condition: pMutex is assumed held and the thread possesses
+ * a Capability.
+ * Post-condition: pMutex is held and the thread possesses
+ * a Capability.
+ */
+void
+yieldToReturningWorker(Mutex* pMutex, Capability** pCap, Condition* pThreadCond)
+{
+ if ( rts_n_waiting_workers > 0 ) {
+ IF_DEBUG(scheduler,
+ fprintf(stderr,"worker thread (%p): giving up RTS token\n", osThreadId()));
+ releaseCapability(*pCap);
+ /* And wait for work */
+ waitForWorkCapability(pMutex, pCap, pThreadCond);
+ IF_DEBUG(scheduler,
+ fprintf(stderr,"worker thread (%p): got back RTS token (after yieldToReturningWorker)\n",
+ osThreadId()));
+ }
+ return;
+}
+
+
+/*
+ * Function: waitForWorkCapability(Mutex*, Capability**, Condition*)
+ *
+ * Purpose: wait for a Capability to become available. In
+ * the process of doing so, updates the number
+ * of tasks currently blocked waiting for a capability/more
+ * work. That counter is used when deciding whether or
+ * not to create a new worker thread when an external
+ * call is made.
+ * If pThreadCond is not NULL, a capability can be specifically
+ * passed to this thread using passCapability.
+ *
+ * Pre-condition: pMutex is held.
+ * Post-condition: pMutex is held and *pCap is held by the current thread
+ */
+
+static Condition *passTarget = NULL;
+static rtsBool passingCapability = rtsFalse;
+
+void
+waitForWorkCapability(Mutex* pMutex, Capability** pCap, Condition* pThreadCond)
+{
+#ifdef SMP
+ #error SMP version not implemented
+#endif
+ IF_DEBUG(scheduler,
+ fprintf(stderr,"worker thread (%p): wait for cap (cond: %p)\n",
+ osThreadId(),pThreadCond));
+ while ( noCapabilities() || (passingCapability && passTarget != pThreadCond)) {
+ if(pThreadCond)
+ {
+ waitCondition(pThreadCond, pMutex);
+ IF_DEBUG(scheduler,
+ fprintf(stderr,"worker thread (%p): get passed capability\n",
+ osThreadId()));
+ }
+ else
+ {
+ rts_n_waiting_tasks++;
+ waitCondition(&thread_ready_cond, pMutex);
+ rts_n_waiting_tasks--;
+ IF_DEBUG(scheduler,
+ fprintf(stderr,"worker thread (%p): get normal capability\n",
+ osThreadId()));
+ }
+ }
+ passingCapability = rtsFalse;
+ grabCapability(pCap);