+
+/*
+ * 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;
+
+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() || (pThreadCond && passTarget != pThreadCond)
+ || (!pThreadCond && passTarget)) {
+ 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()));
+ }
+ }
+ passTarget = NULL;
+ grabCapability(pCap);
+ return;
+}
+
+/*
+ * Function: passCapability(Mutex*, Capability*, Condition*)
+ *
+ * Purpose: Let go of the capability and make sure the thread associated
+ * with the Condition pTargetThreadCond gets it next.
+ *
+ * Pre-condition: pMutex is held and cap is held by the current thread
+ * Post-condition: pMutex is held; cap will be grabbed by the "target"
+ * thread when pMutex is released.
+ */
+
+void
+passCapability(Mutex* pMutex, Capability* cap, Condition *pTargetThreadCond)
+{
+#ifdef SMP
+ #error SMP version not implemented
+#endif
+ rts_n_free_capabilities = 1;
+ signalCondition(pTargetThreadCond);
+ passTarget = pTargetThreadCond;
+ IF_DEBUG(scheduler,
+ fprintf(stderr,"worker thread (%p): passCapability\n",
+ osThreadId()));
+}
+
+