Tom Kelliher, CS42
Oct. 16, 1996
Also locks and condition variables.
In short, no enforcement of mutual exclusion.
(C style)
shared T v; ... region v when B do S;
shared struct { item pool[N]; int count = 0, in = 0, out = 0; } buffer; producer: while (1) { produce into next; region buffer when count < N { pool[in] = next; in = ++in % N; ++count; } } consumer: while(1) { region buffer when count > 0 { next = pool[out]; out = ++out % N; --count; } consume next; }
Associated, by compiler, with each shared variable:
Uses of compiler variables:
Implementation:
mutex.wait(); while (!B) { ++firstCount; if (secondCount > 0) secondDelay.signal(); else mutex.signal(); firstDelay.wait(); --firstCount; ++secondCount; if (firstCount > 0) firstDelay.signal(); else secondDelay.signal(); secondDelay.wait(); --secondCount(); } S; if (firstCount > 0) firstDelay.signal(); else if (secondCount > 0) secondDelay.signal(); else mutex.signal();
Critical region problem: programmer, not designer, decides how shared variables are used once obtained.
Monitor, A C++ class with:
Like a class, with condition variables.
monitor buffer { item pool[N]; int count, in, out; condition nonFull, nonEmpty; public: buffer(); void produce(item next); item consume(void); }; buffer::buffer() { count = in = out = 0; } void buffer::produce(item next) { if (count == N) nonFull.wait(); pool[in] = next; in = ++in % N; ++count; nonEmpty.signal(); } item buffer::consume(void) { item temp; if (count == 0) nonEmpty.wait(); temp = pool[out]; out = ++out % N; --count; nonFull.signal(); return temp; }
Additional variables for each class instance:
Each class method, m(), implemented:
mutex.wait(); m(); if (priorityCount > 0) priority.signal(); else mutex.signal();
Condition wait ( c.wait()):
++cCount; if (priorityCount > 0) priority.signal(); else mutex.signal(); cSem.wait(); --cCount;
Condition signal ( c.signal()):
if (cCount > 0) { ++priorityCount; cSem.signal(); priority.wait(); --priorityCount; }
Multiprocessor support --- can't disable interrupts to achieve mutual exclusion.
Adaptive mutex: