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 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题