Skip to content

Instantly share code, notes, and snippets.

@JeffreyZhao
Created October 26, 2012 05:43
Show Gist options
  • Save JeffreyZhao/3957082 to your computer and use it in GitHub Desktop.
Save JeffreyZhao/3957082 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();
}
@imnull
Copy link

imnull commented Oct 26, 2012

        //俩ThreadStart 把俩方法委托进去
        ThreadStart tsA = new ThreadStart(PrintA);
        ThreadStart tsB = new ThreadStart(PrintB);
        //俩委托调用. acB = null 是因为不赋值后面报未赋值错误.
        AsyncCallback acA, acB = null;

        //PrintA结束委托后,再调用tsB
        acA = new AsyncCallback(delegate(IAsyncResult r)
        {
            tsA.EndInvoke(r);
            Thread.Sleep(37);
            tsB.BeginInvoke(acB, null);
        });
        //PrintB结束委托后,再调用tsA,写成个套套.
        acB = new AsyncCallback(delegate(IAsyncResult r)
        {
            tsB.EndInvoke(r);
            Thread.Sleep(51);
            tsA.BeginInvoke(acA, null);
        });
        //然后就开始死磕
        tsA.BeginInvoke(acA, null);

        //以下是干扰代码 用于测试
        new Thread(delegate() {
            while (true)
            {
                Thread.Sleep(521);
                Console.Write("-");
            }
        }).Start();
        //主线程的干扰
        while (true)
        {
            Thread.Sleep(795);
            Console.Write("=");
        }

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