Skip to content

Instantly share code, notes, and snippets.

@waynebaby
Forked from JeffreyZhao/gist:3957082
Created October 26, 2012 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save waynebaby/3957202 to your computer and use it in GitHub Desktop.
Save waynebaby/3957202 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 AutoResetEvent AEvent=new AutoResetEvent (true );
static AutoResetEvent BEvent = new AutoResetEvent(false);
static void PrintA()
{
AEvent.WaitOne();
Console.WriteLine("A");
BEvent.Set();
}
static void PrintB()
{
BEvent.WaitOne();
Console.WriteLine("B");
AEvent.Set();
}
// DO NOT touch the code below
for (var i = 0; i < 10; i++)
{
new Thread(() => {
while (true) {
PrintA();
PrintB();
}
}).Start();
}
@waynebaby
Copy link
Author

https://gist.github.com/3957202 刚才没理解题目。。。

@cycyyy
Copy link

cycyyy commented Oct 26, 2012

// 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 AutoResetEvent AEvent=new AutoResetEvent (true );

    static void PrintA()
    {
        AEvent.WaitOne();
        Console.WriteLine("A");

    }

    static void PrintB()
    {

        Console.WriteLine("B");
        AEvent.Set();
    }

// DO NOT touch the code below

for (var i = 0; i < 10; i++)
{
new Thread(() => {
while (true) {
PrintA();
PrintB();
}
}).Start();
}

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