This is a bit of a stupid question, but here goes.
I'm programming a lightswitch (a group semaphore). It works by passing a static semaphore into the lightswitch constructor. When a thread calls the acquire method on the lightswitch, it acquires the semaphore. I have, say, four threads, two acquire the lightswitch, two acquire the semaphore. The first lightswitch thread acquires the lightswitch, thus acquiring the semaphore. This blocks the two threads who try to acquire the semaphore, but the other thread that acquires the lightswitch can go through. The two trying to acquire the semaphore are blocked until the last thread in the lightswitch is finished.
Here's some code to demonstrate this:
Test class with the static semaphore, declaring the lightswitch.
class TestLightSwitch
{
private static Utilities.LightSwitch ls;
private static Utilities.Semaphore sem = new Utilities.Semaphore();
static void Main(string[] args)
{
sem.Release();
ls = new SeansConcurrencyUtilities.LightSwitch(sem);
Lightswitch has a copy of the semaphore:
public class LightSwitch
{
private readonly Utilities.Semaphore sem;
public LightSwitch(Semaphore s)
{
sem = s;
What I don't understand is why it works. Why is it that thread a, goes into the lightswitch, acquires the lightswitch's copy of the semaphore, and that affects the original semaphore, so when thread b acquires the original semaphore, it's blocked? It seems to be like pass by reference or something.