crazyerer 2017-02-14 03:57 采纳率: 50%
浏览 1026

c#多线程的Interkock.Exchange方法执行问题

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace 多线程LOCK.InterLock
{//打印机:有三台计算机同事发出打印指令,使用Exchange实现锁
class Program
{

    class Printerwithinterlocktest
    {


        public static int computernum = 3;//计算机数量
        public static void openthread()
        {
            Thread thread;
            Random random = new Random();
            thread = new Thread(printerproc);
            thread.Name = "mythread";
            thread.Start();

       }
        private static void printerproc()

        {
            userprint();
            Thread.Sleep(1000);
        }

        public static int usingprint = 0;//初始化正在打印状态
        private static bool userprint()
        {
            if ( Interlocked.Exchange(ref usingprint, 1) ==0)
            {
                int c = 1;
                Console.WriteLine(Thread.CurrentThread.Name + "acquired the lock");
                Thread.Sleep(5000);
                Console.WriteLine(Thread.CurrentThread.Name + "existed the lock");
                Interlocked.Exchange(ref usingprint, 0);

                return true;
            }
            else
            {
                int c = 2;
                Console.WriteLine(Thread.CurrentThread.Name + "is denited the lock");
                return false;
            }
        }
    }
  static void Main(string[] args)
    {
        Printerwithinterlocktest.openthread();
        Console.ReadKey();
    }
}

}
这段代码在执行到if ( Interlocked.Exchange(ref usingprint, 1) ==0)时,按照调试结果看是继续执行而不是跳入到Else,想问问到底是先执行Exchange方法还是先比较呢,为什么

  • 写回答

1条回答 默认 最新

  • crazyerer 2017-02-14 06:56
    关注

    图片说明运行结果

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。