zoukankan      html  css  js  c++  java
  • Thread Synchronization Queue with Boost

    介绍:当开发一个多线程程序时,同步是一个很大的问题。如果你的程序需要数据流包,那么用队列是个好办法。

    你可以在 http://www.boost.org/ 发现 boost 库和文档,从它的网站可以看出用boost的优势:

    In a word, Productivity. Use of high-quality libraries like Boost speeds initial development, results in fewer bugs, reduces reinvention-of-the-wheel, and cuts long-term maintenance costs. And since Boost libraries tend to become de facto or de jure standards, many programmers are already familiar with them.

    下面介绍用boost synchronization class(boost 同步类)来实现。

    代码实现:

    在例子中,用了线程同步模型来说明producer-consumer(生产者--消费者模型),producer线程创建数据并插入到队列中,consumer线程使用数据并从队列中删除数据。使用了mutex对象来保持两个线程的同步。

    用不同的解决方法来实现线程的同步队列,然后比较了它们的优势与不足。

    1. SynchronizedDequeue: is a double-ended queue, implemented with STL deque.
    2. SychronizedVector: is a ring or cycle queue, implemented with STL vector.
    3. SychronizedVectorNB: is the no-blocking version of SychronizedVector.

    头文件和接口定义:

    Code

    接口实现:

    SynchronizedDequeue有动态的队列大小,好处是如果producer比consumer快,没有数据会丢失,全部的数据将被consumer接收。不足是受内存更大的影响。当要插入队列时分配内存,当consumer线程接收到数据后释放内存。因为会出现内存分配和释放多次,降低了对在同一过程中更大的内存回收。

    Code

    SychronizedVector使用了固定大小的队列来避免内存开销,但当有新数据来,它会覆盖旧数据,并从队列中刷新出去。

    Code

    SychronizedVectorNB不会被阻塞,无论是生产者还是消费者线程。优点在于,如果有一些其他activity需要被处理在队列访问线程的过程中,那么non-block将保证响应时间。当线程试图拥有该mutex对象,上述两个队列可以阻塞线程。如果一个线程拥有mutex,那么发生exception时,其他线程也将被阻塞。缺点是,当它不能拥有lock,添加数据到队列时可能失败,那么caller需要再次添加相同的数据。

    Code

    下面是producer线程代码:

    Code

    下面是consumer线程代码:
    Code


    下面是main线程代码:

    Code

    在测试代码中,创建了五个producers,五个consumers和五个队列。每个producer都有其伙伴consumer通过使用相同的队列链接。可以验证,如果创建的每个数据包的数据,都是consumer线程通过它的数据包ID处理的。

    原英文链接:http://www.codeproject.com/Articles/442452/Thread-Synchronization-Queue-with-Boost

  • 相关阅读:
    [AWS] Export and Import Data from DynamoDB Table 从 DynamoDB 数据库中导入和导出数据
    [LeetCode] 944. Delete Columns to Make Sorted 删除列使其有序
    [LeetCode] 943. Find the Shortest Superstring 找到最短的超级字符串
    [LeetCode] 942. DI String Match 增减DI字符串匹配
    [LeetCode] 941. Valid Mountain Array 验证山形数组
    [LeetCode] 940. Distinct Subsequences II 不同的子序列之二
    [LeetCode] 939. Minimum Area Rectangle 面积最小的矩形
    [LeetCode] 938. Range Sum of BST 二叉搜索树的区间和
    [LeetCode] 937. Reorder Data in Log Files 日志文件的重新排序
    [LeetCode] 936. Stamping The Sequence 戳印序列
  • 原文地址:https://www.cnblogs.com/klcf0220/p/4065163.html
Copyright © 2011-2022 走看看