none
如何动态的控制并行程序线程的切换

    问题

  • 如题, 并行程序中各个线程的切换是由操作系统完成,有没有什么方法可以动态的控制各个线程的切换?

    比如,有函数foo():

    foo() { statement a; statement b; }

    有两个线程运行foo函数,希望某一次运行是thread1_a->thread2_a->thread1_b->thread2_b, 另一次是thread1_a->thread1_b->thread2_a->thread2_b,可以动态控制。期待您的回答,谢谢。

    另外还有一个问题,可否使用profiler API获取当前运行线程的id号及语句id/token号,或有什么方法获得?我希望能够跟踪并行程序的运行状况。

    2016年1月28日 12:38

答案

  • 您好 ClarkChen,

    >>希望某一次运行是thread1_a->thread2_a->thread1_b->thread2_b

    这需要控制线程执行的顺序,我们需要在线程内部判断当前运行的是哪个线程,然后决定是空转等待还是继续执行,我写了个示例供你参考。

    class Program
    {
        static void Main(string[] args)
        {
            Thread t1 = new Thread(foo);
            Thread t2 = new Thread(foo);
    
            t1Id = t1.ManagedThreadId;
            t2Id = t2.ManagedThreadId;
    
            t1.Start();
            t2.Start();
            Console.Read();
        }
    
        static int t1Id;
        static int t2Id;
    
        static bool step1Ready = false;
        static bool step2Ready = false;
    
        static Barrier barrier = new Barrier(2);
    
        static void foo()
        {
            if (System.Threading.Thread.CurrentThread.ManagedThreadId == t2Id)
            {
                while (true)
                {
                    if (step1Ready == true)
                    {
                        break;
                    }
                }
            }
    
            Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + "-- Statement1");
    
            if (System.Threading.Thread.CurrentThread.ManagedThreadId == t1Id)
            {
                step1Ready = true;
            }
    
            barrier.SignalAndWait();
    
            if (System.Threading.Thread.CurrentThread.ManagedThreadId == t2Id)
            {
                while (true)
                {
                    if (step2Ready == true)
                    {
                        break;
                    }
                }
            }
    
            Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + "-- Statement2");
    
            if (System.Threading.Thread.CurrentThread.ManagedThreadId == t1Id)
            {
                step2Ready = true;
            }
        }
    }
    Best Regards,
    Li Wang

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2016年1月29日 3:11