c# 锁 Interlocked 操作
//定义原子变量
int mituxInt = -1; //原子级别+1值,如果>=0,说明当前锁为空,可以执行,避免重复执行 if (Interlocked.Increment(ref mituxInt) <= 0) { if (_serverThread == null || (_serverThread.IsAlive == false)) { AutoConnect = isAutoConn; _serverThread = new Thread(new ThreadStart(ThreadConnectServer)); _serverThread.IsBackground = true; _serverThread.Start(); } Interlocked.Exchange(ref mituxInt, -1); }
int lock2=0; private void FuncMustDo() { //交换lock2 和1,返回lock2以前的值,这个和lock不一样的是,可以加其他条件 while (Interlocked.Exchange(ref lock2, 1) != 0) { } //啪嗒啪嗒执行操作
//置0 Thread.VolatileWrite(ref lock2, 0);//Thread.VolatileWrite执行一个原子写入操作,它的每次执行都具有释放语义 }