Skip to content

Instantly share code, notes, and snippets.

@baiyanhuang
Forked from JeffreyZhao/gist:3957082
Created October 26, 2012 08:07
Show Gist options
  • Save baiyanhuang/3957561 to your computer and use it in GitHub Desktop.
Save baiyanhuang/3957561 to your computer and use it in GitHub Desktop.
// The code below would print overlapped A and B sequences like:
// ...
// A
// A
// B
// B
// ...
//
// Please add multi-threading protection code to make sure that
// As and Bs are printed in the order of:
// ...
// A
// B
// A
// B
// ...
static void PrintA()
{
Console.WriteLine("A");
}
static void PrintB()
{
Console.WriteLine("B");
}
// DO NOT touch the code below
for (var i = 0; i < 10; i++)
{
new Thread(() => {
while (true) {
PrintA();
PrintB();
}
}).Start();
}
@baiyanhuang
Copy link
Author

using the lock statement or monitor:

using System;
using System.Threading;

class Program
{
static Object obj = new Object();

static void PrintA()
{
    Monitor.Enter(obj);
    Console.WriteLine("A");
}

static void PrintB()
{
    Console.WriteLine("B");
    Monitor.Exit(obj);
}

// DO NOT touch the code below

public static void Main()
{
    for (var i = 0; i < 10; i++)
    {
        new Thread(() => {
            while (true) {
                //lock(obj) - solution 2
                {
                    PrintA();
                    PrintB();
                }
            }
        }).Start();
    }
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment