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

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的引用计数使用的。
    你要看你具体想干啥,才能知道你要用啥。

    评论

报告相同问题?

悬赏问题

  • ¥20 Python安装cvxpy库出问题
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题