实现一个同步队列
并且多线程竞争读写。
实例如下:
template<typename T>
class SyncQueue
{
public:
SyncQueue(int maxSize) : m_maxSize(maxSize) {}
void put(const T& value)
{
std::lock_guard<std::mutex> locker(m_mutex);
while (isFull())
{
cout << "queue full! waiting..." << endl;
m_notFull.wait(m_mutex);
}
m_queue.push_back(value);
std::this_thread::sleep_for(std::chrono::seconds(1));
m_notEmpty.notify_one();
}
T take()
{
std::lock_guard<std::mutex> locker(m_mutex);
while (isEmpty())
{
cout << "queue empty! waiting..." << endl;
m_notEmpty.wait(m_mutex);
}
T temp = m_queue.front();
m_queue.pop_front();
std::this_thread::sleep_for(std::chrono::seconds(1));
m_notFull.notify_one(); //队列不空
return temp;
}
bool empty()
{
std::lock_guard<std::mutex> locker(m_mutex);
return m_queue.empty();
}
bool full()
{
std::lock_guard<std::mutex> locker(m_mutex);
return m_queue.size() == m_maxSize;
}
size_t size()
{
std::lock_guard<std::mutex> locker(m_mutex);
return m_queue.size();
}
private:
bool isFull() const
{
return m_queue.size() == m_maxSize;
}
bool isEmpty()
{
return m_queue.empty();
}
private:
std::list<T> m_queue;
std::mutex m_mutex;
std::condition_variable_any m_notEmpty;
std::condition_variable_any m_notFull;
int m_maxSize;
};
SyncQueue<int> Queue(3);
static int gValue = 0;
void add()
{
while (true)
{
int value = gValue++;
Queue.put(value);
cout << "thread :" << std::this_thread::get_id() << " put :" << value << " curr size:"<<Queue.size() << endl;
}
}
void sub()
{
while (true)
{
int value = Queue.take();
cout << "thread :" << std::this_thread::get_id() << " take:"<<value << " curr size:" << Queue.size() << endl;
}
}
int main()
{
std::thread t1(add);
std::thread t2(add);
std::thread t3(sub);
t1.join();
t2.join();
t3.join();
return 0;
}
运行解决如下:
这里量个线程add操作,一个线程sub操作。
条件变量的另一种用法
m_notFull.wait(m_mutex, [this]
{
cout << "queue full! waiting..." << endl;
return !isFull();
});