-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlockqueue.h
40 lines (36 loc) · 938 Bytes
/
lockqueue.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#pragma once
#include <queue>
#include <thread>
#include <mutex> // pthread_mutex_t
#include <condition_variable> // pthread_condition_t
// 异步写日志的日志队列
template <typename T>
class LockQueue
{
private:
std::queue<T> m_queue;
std::mutex m_mutex;
std::condition_variable m_condition_variable;
public:
// 多个worker线程都会写日志queue
void Push(const T &data)
{
// 加锁
std::lock_guard<std::mutex> lock(m_mutex);
m_queue.push(data);
m_condition_variable.notify_one();
}
// 一个线程读日志queue,写日志文件
T Pop()
{
std::unique_lock<std::mutex> lock(m_mutex);
while (m_queue.empty())
{
// 日志队列为空,线程进入wait状态
m_condition_variable.wait(lock);
}
T data = m_queue.front();
m_queue.pop();
return data;
}
};