-
-
Save haijunxiong/3957745 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
// ... | |
private static Semaphore semA = new Semaphore(1,1); | |
private static Semaphore semB = new Semaphore(0,1); | |
static void PrintA() | |
{ | |
semA.WaitOne(); | |
Console.WriteLine("A"); | |
semB.Release(); | |
} | |
static void PrintB() | |
{ | |
semB.WaitOne(); | |
Console.WriteLine("B"); | |
semA.Release(); | |
} | |
// 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
private static Semaphore semA = new Semaphore(1,1);
private static Semaphore semB = new Semaphore(0,1);
// DO NOT touch the code below
for (var i = 0; i < 10; i++)
{
new Thread(() => {
while (true) {
PrintA();
PrintB();
}
}).Start();
}