简体   繁体   English

锁定线程与进程

[英]Locking thread vs process

Here is a piece of sample code that uses locks: 这是一段使用锁的示例代码:

public static class Account  
{  
    decimal balance;  
    private static Object thisLock = new Object();  

    public static void Withdraw(decimal amount)  
    {  
        lock (thisLock)  
        {  
            if (amount > balance)  
            {  
                throw new Exception("Insufficient funds");  
            }  
            balance -= amount;  
        }  
    }  
} 

Lets say this method is called by an web api. 可以说此方法是由网络api调用的。 And the API is hosted on IIS. 该API托管在IIS上。 My understanding is that when a request is received by IIS, a new worker process can be created. 我的理解是,当IIS收到请求时,可以创建一个新的工作进程。 So if two concurrent requests are received, and if they are being are executed on two separate processes, then the above lock is quite useless and I need to use some kind of inter-process blocking. 因此,如果接收到两个并发请求,并且正在两个单独的进程上执行这些请求,那么上述锁定将毫无用处,我需要使用某种进程间阻塞。 Is my understanding correct? 我的理解正确吗?

Different requests will server by different thread so yes, the lock is valid. 不同的请求将通过不同的线程进行服务器处理,因此是的,锁是有效的。 But : when a server farm is used (like multiple azure web app instances) this lock will only work for one instance. 但是 :当使用服务器场(例如多个Azure Web应用程序实例)时,此锁定仅适用于一个实例。 So, in the world of distributed programming you will have to rethink your design. 因此,在分布式编程的世界中,您将不得不重新考虑您的设计。 Too many locks will slow down the system as well as requests have to wait for their turn. 太多的锁会使系统变慢,并且请求必须等待轮到他们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM