Skip to content

Instantly share code, notes, and snippets.

@wsky
Forked from JeffreyZhao/gist:3957082
Created October 26, 2012 06:10
Show Gist options
  • Save wsky/3957189 to your computer and use it in GitHub Desktop.
Save wsky/3957189 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 object LOCK = new object();
static bool A = true;
static void PrintA()
{
lock (LOCK)
{
if (A)
{
Console.WriteLine("A");
A = false;
}
}
}
static void PrintB()
{
lock (LOCK)
{
if (!A)
{
Console.WriteLine("B");
A = true;
}
}
}
// DO NOT touch the code below
for (var i = 0; i < 10; i++)
{
new Thread(() => {
while (true) {
PrintA();
PrintB();
}
}).Start();
}
@wsky
Copy link
Author

wsky commented Oct 26, 2012

要求很简单 就不上复杂的同步手段了:)

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