今天查看项目代码的时候发现下面这段代码:


1
internal
MoveTask Dequeue(
string
host)
2 {
3 if (host == null )
4 throw new ArgumentNullException( " host " );
5
6 lock (m_QueueLock)
7 {
8 if ( ! m_MoveTaskQueueDictionary.ContainsKey(host) || (m_MoveTaskQueueDictionary[host].Count == 0 ))
9 return null ;
10 }
11
12 lock (m_QueueLock)
13 {
14 return m_MoveTaskQueueDictionary[host].Dequeue();
15 }
16 }
2 {
3 if (host == null )
4 throw new ArgumentNullException( " host " );
5
6 lock (m_QueueLock)
7 {
8 if ( ! m_MoveTaskQueueDictionary.ContainsKey(host) || (m_MoveTaskQueueDictionary[host].Count == 0 ))
9 return null ;
10 }
11
12 lock (m_QueueLock)
13 {
14 return m_MoveTaskQueueDictionary[host].Dequeue();
15 }
16 }
当时这段代码实现时分了两个Lock为的就是对锁的晚占用,早释放。没想到却带来了多线程环境下可能发生的隐患:某个时刻某个Host的队列长度刚好等于1,这时线程A拥有了锁,那么在第一个Lock检查时该Host队列长度大于0,退出锁。此时另外一个线程B在A退出锁之后也进入了锁,也在第一个Lock检查时发现同一个Host的队列长度大于0,然后退出锁,准备进入第二个Lock。这时A线程由于B线程退出了锁,从而得以进入第二个Lock,对队列执行Dequeue方法后安全退出了锁。然后B线程进入锁执行Dequeue方法,这时队列为空,从而引发


1
internal
MoveTask Dequeue(
string
host)
2 {
3 if (host == null )
4 throw new ArgumentNullException( " host " );
5
6 lock (m_QueueLock)
7 {
8 if ( ! m_MoveTaskQueueDictionary.ContainsKey(host) || (m_MoveTaskQueueDictionary[host].Count == 0 ))
9 return null ;
10
11 return m_MoveTaskQueueDictionary[host].Dequeue();
12 }
13 }
2 {
3 if (host == null )
4 throw new ArgumentNullException( " host " );
5
6 lock (m_QueueLock)
7 {
8 if ( ! m_MoveTaskQueueDictionary.ContainsKey(host) || (m_MoveTaskQueueDictionary[host].Count == 0 ))
9 return null ;
10
11 return m_MoveTaskQueueDictionary[host].Dequeue();
12 }
13 }