舞动的代码 2017-03-27 06:37 采纳率: 0%
浏览 2234

C# 中线程的互锁(Interlock),那位大神能帮忙看看

最近在使用Interlock时,出现读值错误,所以写了一个demo,有大神帮忙看看有什么问题。

 namespace ThreadDemo
{
    class Tester
    {
        private int counter = 0;
        static void Main(string[] args)
        {
            //make an instance of this class
            Tester t = new Tester();
            //run outside static Main
            t.DoTest();
            Console.ReadKey();
        }

        private void DoTest()
        {
            Thread t1 = new Thread(new ThreadStart(Incrementer));
            t1.IsBackground = true;
            t1.Name = "ThreadOne";
            t1.Start();
            Console.WriteLine("Started thread {0}",t1.Name);


            Thread t2 = new Thread(new ThreadStart(Incrementer));
            t2.IsBackground = true;
            t2.Name = "ThreadTwo";
            t2.Start();
            Console.WriteLine("Started thread {0}", t2.Name);

            t1.Join();
            t2.Join();

            //等待所有的线程都结束
            Console.WriteLine("All my threads are done.");
        }
        //线程调用的函数
        private void Incrementer()
        {
            //Console.WriteLine("Incrementer:{0}",counter);
            try
            {
                while (counter < 10)
                {
                    //使用互锁
                    Interlocked.Increment(ref counter);
                    //线程挂起
                    Thread.Sleep(1);
                    //显示结果
                    Console.WriteLine("Thread {0}.Incrementer:{1}",Thread.CurrentThread.Name,counter);
                }
            }
            catch(ThreadInterruptedException)
            {
                Console.WriteLine("Thread {0} Interlocked!Cleaning up ...",Thread.CurrentThread.Name);
            }
            finally
            {
                Console.WriteLine("Thread {0} Exiting.",Thread.CurrentThread.Name);
            }
        }
    }
}

结果显示如下图:
图片说明

我已经使用Interlocked进行了锁定,为什么线程2在线程1没有结束的时候会改变变量的值,求大神帮忙看看。

  • 写回答

2条回答

  • yangbo50304 2017-03-27 07:46
    关注

    如果要让线程2等待线程1完毕后再执行线程2,用lock()不就得了,Interlocked本来就是对lock的引用计数使用的。
    你要看你具体想干啥,才能知道你要用啥。

    评论

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services