- nat i;
- Capability *cap, *prev;
- cap = NULL;
- prev = NULL;
- for (i = 0; i < n; i++) {
- cap = stgMallocBytes(sizeof(Capability), "initCapabilities");
- initCapability(cap);
- cap->link = prev;
- prev = cap;
- }
- free_capabilities = cap;
- rts_n_free_capabilities = n;
- IF_DEBUG(scheduler,fprintf(stderr,"scheduler: Allocated %d capabilities\n", n_free_capabilities););
+ // Pre-condition: pMutex is assumed held, the current thread
+ // holds the capability pointed to by pCap.
+
+ if ( rts_n_waiting_workers > 0 || passingCapability || !ANY_WORK_TO_DO()) {
+ IF_DEBUG(scheduler,
+ if (rts_n_waiting_workers > 0) {
+ sched_belch("worker: giving up capability (returning wkr)");
+ } else if (passingCapability) {
+ sched_belch("worker: giving up capability (passing capability)");
+ } else {
+ sched_belch("worker: giving up capability (no threads to run)");
+ }
+ );
+ releaseCapability(*pCap);
+ *pCap = NULL;
+ }
+
+ // Post-condition: either:
+ //
+ // 1. *pCap is NULL, in which case the current thread does not
+ // hold a capability now, or
+ // 2. *pCap is not NULL, in which case the current thread still
+ // holds the capability.
+ //
+ return;
+}
+
+
+/* ----------------------------------------------------------------------------
+ * waitForCapability( 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.
+ * ------------------------------------------------------------------------- */
+
+void
+waitForCapability( Mutex* pMutex, Capability** pCap, Condition* pThreadCond )
+{
+ // Pre-condition: pMutex is held.
+
+ while ( noCapabilities() ||
+ (passingCapability && passTarget != pThreadCond) ||
+ !ANY_WORK_TO_DO()) {
+ IF_DEBUG(scheduler,
+ sched_belch("worker: wait for capability (cond: %p)",
+ pThreadCond));
+
+ if (pThreadCond != NULL) {
+ waitCondition(pThreadCond, pMutex);
+ IF_DEBUG(scheduler, sched_belch("worker: get passed capability"));
+ } else {
+ rts_n_waiting_tasks++;
+ waitCondition(&thread_ready_cond, pMutex);
+ rts_n_waiting_tasks--;
+ IF_DEBUG(scheduler, sched_belch("worker: get normal capability"));
+ }
+ }
+ passingCapability = rtsFalse;
+ grabCapability(pCap);
+
+ // Post-condition: pMutex is held and *pCap is held by the current thread
+ return;