在实际的项目应用中,涉及到很多队列,但是队列的实际使用却受到多线程安全的影响,为了屏蔽这些影响,需要使用到互斥锁,如下是自己实现的一个线程安全队列

 1 template<typename T>
 2 class CRequestQueue
 3 {
 4 
 5 public:
 6     CRequestQueue() {}
 7     ~CRequestQueue() 
 8     {
 9         if (!theQueue_.empty())
10         {
11             theQueue_.clear();
12         }
13 
14     }
15 
16     int QueuePush(const T &pt) 
17     {
18         boost::mutex::scoped_lock oLock(m_oMutex);
19         theQueue_.push_back(pt);
20         return theQueue_.size();
21     }
22 
23     T QueuePop() 
24     {
25         boost::mutex::scoped_lock oLock(m_oMutex);
26         if (theQueue_.size() > 0) 
27         {
28             T oThread = theQueue_.front();
29             theQueue_.pop_front();
30             return oThread;
31         }
32 
33         return m_nullObject;
34     }
35 
36     void QueueErase(T &Object) 
37     {
38         boost::mutex::scoped_lock oLock(m_oMutex);
39         typedef typename list<T>::iterator iter_thread;
40         for (iter_thread it = theQueue_.begin(); it != theQueue_.end();) 
41         {
42             if (Object == *it) 
43             {
44                 theQueue_.erase(it++);
45                 break;
46             }
47             else 
48             {
49                 ++it;
50             }
51         }
52     }
53 
54     void QueueClean()
55     {    
56         boost::mutex::scoped_lock oLock(m_oMutex);
57         if (!theQueue_.empty())
58         {
59             theQueue_.clear();
60         }
61 
62         return;
63     }
64 
65     int QueueLength() 
66     {
67         boost::mutex::scoped_lock oLock(m_oMutex);
68         return theQueue_.size();
69     }
70 
71     bool IsQueueEmpty()
72     {
73         boost::mutex::scoped_lock oLock(m_oMutex);
74         return theQueue_.empty();
75     }
76 
77 public:
78     boost::mutex m_oMutex;
79 
80 private:
81     std::list<T> theQueue_;
82     T m_nullObject;
83 };

 

posted on 2012-12-26 19:07  寻她千百度  阅读(2746)  评论(0编辑  收藏  举报