Created
February 22, 2019 08:23
-
-
Save hmenn/34d300ba1ed0eb0ed36a6a9b0af1a3ad to your computer and use it in GitHub Desktop.
Basic thread safe queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <thread> | |
#include <mutex> | |
#include <queue> | |
#include <chrono> | |
template <class T> | |
class TSafeQueue{ | |
public: | |
TSafeQueue(){ | |
} | |
void push(T obj){ | |
std::lock_guard<std::mutex> guard(m_mtx); | |
m_queue.push(obj); | |
} | |
T pop(){ | |
std::lock_guard<std::mutex> guard(m_mtx); | |
if(m_queue.empty()) | |
return T(); | |
T obj = m_queue.front(); | |
m_queue.pop(); | |
return obj; | |
} | |
int size(){ | |
std::lock_guard<std::mutex> guard(m_mtx); | |
return m_queue.size(); | |
} | |
bool empty(){ | |
std::lock_guard<std::mutex> guard(m_mtx); | |
return m_queue.empty(); | |
} | |
private: | |
std::mutex m_mtx; | |
std::queue<T> m_queue; | |
}; | |
int main() { | |
TSafeQueue<std::string> tsq; | |
std::thread producer([&](){ | |
for(int i=0;i<100;++i){ | |
tsq.push(std::to_string(i)); | |
std::cerr<<"Push:"<<i<<std::endl; | |
std::this_thread::sleep_for(std::chrono::milliseconds(50)); | |
} | |
}); | |
std::thread consumer([&](){ | |
for(int i=0;i<100;++i){ | |
std::string data = tsq.pop(); | |
std::cerr<<"Pop"<<data<<std::endl; | |
std::this_thread::sleep_for(std::chrono::milliseconds(100)); | |
} | |
}); | |
producer.join(); | |
consumer.join(); | |
std::cerr<<"Size:"<<tsq.size()<<std::endl; | |
std::cerr<<"Is Empty:"<<tsq.empty()<<std::endl; | |
std::cerr<<"Done"<<std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment