场景是这样,假设有一台设备会触发类型为Alarm的告警信号,并把信号添加到一个Queue结构中,每隔一段时间这个Queue会被遍历检查,其中的每个Alarm都会调用一个相应的处理方法。问题在于,检查机制是基于多线程的,有潜在的并发可能,当某个Alarm被添加的同时刚好又在遍历Queue,就会抛出异常说Queue发生改变。产生问题的代码如下:

public class AlarmQueueManager
{
public ConcurrentQueue<Alarm> alarmQueue = new ConcurrentQueue<Alarm>();
System.Timers.Timer timer; public AlarmQueueManager()
{
timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
} void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
DeQueueAlarm();
} private void DeQueueAlarm()
{
try
{
foreach (Alarm alarm in alarmQueue)
{
SendAlarm(alarm);
alarmQueue.TryDequeue();
//having some trouble here with TryDequeue..
}
}
catch
{
}
}
}

那么如何让DeQueueAlarm保证线程安全呢?

为了简化描述,用以下两种写法来对比介绍。

// 写法一
private void DeQueueAlarm()
{
Alarm alarm;
while (alarmQueue.TryDequeue(out alarm))
SendAlarm(alarm);
} // 写法二
private void DeQueueAlarm()
{
foreach (Alarm alarm in alarmQueue)
SendAlarm(alarm);
}

参考MSDN的说法:ConcurrentQueue<T>.GetEnumerator

The enumeration represents a moment-in-time snapshot of the contents of the queue. It does not reflect any updates to the collection after GetEnumerator was called. The enumerator is safe to use concurrently with reads from and writes to the queue.

所以两种写法在多线程并发访问的差别就是,使用TryQueue会确保每个Alarm只会被处理一次,但哪个线程处理哪个Alarm是不确定的。使用foreach循环会确保参与争用的所有线程都同等无差别地访问Queue的全部Alarm,就像Queue被重复处理了n遍。因此,如果想要严格控制每个Alarm只会被处理一次,用完就移除的话,那就使用第一种写法。

原文:Thread safe queue - Enqueue / Dequeue

确保线程安全下使用Queue的Enqueue和Dequeue的更多相关文章

  1. java线程安全之并发Queue

    关闭 原 java线程安全之并发Queue(十三) 2017年11月19日 23:40:23 小彬彬~ 阅读数:12092更多 所属专栏: 线程安全    版权声明:本文为博主原创文章,未经博主允许不 ...

  2. 获取其他线程的数据用 queue, 多进程Q

    获取其他线程的数据用 queue, 多进程Q

  3. tensorflow队列tf.FIFOQueue | enqueue | enqueue_many | dequeue | dequeue_many

    关于队列的相关知识,盗用一张https://blog.csdn.net/HowardWood/article/details/79406891的动态图 import tensorflow as tf ...

  4. Perl线程队列:Thread::Queue

    (Thread::Queue)队列数据结构(FIFO)是线程安全的,它保证了某些线程从一端写入数据,另一些线程从另一端读取数据.只要队列已经满了,写入操作就自动被阻塞直到有空间支持写操作,只要队列空了 ...

  5. python 线程之 数据同步 Queue

    Queue:将数据从一个线程发往另外一个线程比较通用的方式是使用queue模块的Queue类 1, 首先创建一个Queue模块的对象,创建Queue对象可以传递maxsize也可以不传递 2. 使用对 ...

  6. 装个蒜。学习下dispatch queue

    dispatch queue的真髓:能串行,能并行,能同步,能异步以及共享同一个线程池. 接口: GCD是基于C语言的APT.虽然最新的系统版本中GCD对象已经转成了Objective-C对象,但AP ...

  7. 三种进程和线程数据共享模块方法Queue》Pipe》manager

    >>>>线程中的queue import threading import queue def f(qq): print("in child",qq.qsi ...

  8. 多线程深入理解和守护线程、子线程、锁、queue、evenet等介绍

    1.多线程类的继承 import threading import time class MyThreading(threading.Thread): def __init__(self,n): su ...

  9. 进程与线程的通信机制----Queue

    进程运行时候变量是隔离的,线程间共享全局变量. 进程: from multiprocessing import Process from threading import Thread def get ...

随机推荐

  1. 安卓开机logo和开机动画的几种实现方法

    安卓4.2可用方法2-4,第一种方法未验证. 从理论上来说,android 有4个开机启动画面. 第一个应该是U-BOOT的启动画面,有些设备为了满足按动电源即有显示,在UBOOT里加了开机画面,实现 ...

  2. VMware Workstation “以独占方式锁定此配置文件失败。可能其它正在运行VMware进程在使用此配置文件”

    VMware Workstation客户机异常关闭之后,再启动时提示“以独占方式锁定此配置文件失败...”. 解决方法: 进入客户机的安装目录(注意,非VMware的安装目录),删除所有后缀为lck的 ...

  3. Docker Compose部署 nginx代理Tomcat集群

    一.简介 使用Docker镜像部署Nginx代理的多个Tomcat集群: 使用Dockerfile构建nginx镜像 使用Dockerfile构建tomcat镜像 mysql镜像使用docker hu ...

  4. python基础之列表list元组tuple

    作者:tongqingliu 转载请注明出处:http://www.cnblogs.com/liutongqing/p/7041763.html python基础之列表list元组tuple 列表li ...

  5. GAE、SAE与BAE的对比分析(百度云)

    https://blog.csdn.net/zhongguomao/article/details/53282307 https://cloud.baidu.com/event/experience/ ...

  6. android-基础编程-RecyclerView

    以后android-基础编程*都是控件demo里面的,不再累赘重写.直接介绍控件使用. RecyclerView is a more advanced and flexible version of ...

  7. android textview支持多种格式跳转

    http://www.linuxidc.com/Linux/2011-08/40530p2.htm 1.android:autoLink属性,使TextView中链接手机号码/网页/邮件/地图 and ...

  8. PAT甲级 1121. Damn Single (25)

    1121. Damn Single (25) 时间限制 300 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue "Dam ...

  9. WP8整合Bing应用,生活有求Bing

    在Windows 8中,Bing应用一直随系统而存在,提供多样化的资讯.它们是我的“御用”App,因为可以根据我的使用习惯对应用进行定制. 在Windows Phone 8系统第三次官方更新之后, B ...

  10. 《mysql必知必会》学习_第七章_20180730_欢

    第七章:数据过滤 P43 select prod_id,prod_price,prod_name from products where vend_id =1003 and prod_price &l ...