多线程与同步的理解

1.多线程中有个共享概念,如果多个线程同时对一个对象都有操作权限,就会出现竞争的情况,这样也造成改对象的不稳定性。

2.对于共享造成的数据紊乱,有个根本的解决办法,就是不一定通过共享方案解决一个问题,可以重新设计代码结构,移除共享方案。

共享数据的同步方案整理:

1.lock

在多线程中使用lock一个对象,lock易造成死锁,设计需谨慎。

2.Interlocked

为多个线程共享的变量提供原子操作。相比lock的好处不会出现死锁。

3.AutoResetEvent

新实例初始化 AutoResetEvent 使用 Boolean 值,该值指示是否将初始状态设置为终止状态的类。




        private static AutoResetEvent workerEvent = new AutoResetEvent(false);
        private static AutoResetEvent mainEvent = new AutoResetEvent(false);

        static void Process(int seconds)
        {
            Console.WriteLine("Starting a long running work....");
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            Console.WriteLine("Work is done");
            workerEvent.Set();//步骤2
            Console.WriteLine("Waiting for a main thread to complete its work");
            mainEvent.WaitOne();//步骤3

            Console.WriteLine("Starting second operation...");
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            Console.WriteLine("Work is done!");
            workerEvent.Set();//步骤6
        }

        static void Main(string[] args)
        {
            var t = new Thread(()=>Process(10));
            t.Start();

            Console.WriteLine("Waiting for another thread to complete work");
            workerEvent.WaitOne();//步骤1
            Console.WriteLine("First operation is complete");
            Console.WriteLine("Perfoming an operation on a main thread");
            Thread.Sleep(TimeSpan.FromSeconds(5));
            mainEvent.Set();//步骤4
            Console.WriteLine("Now running the second operation on a second thread");
            workerEvent.WaitOne();//步骤5
            Console.WriteLine("Second operation is completed");
            //Console.ReadKey();
        }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值