Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- #include <mutex>
- #include <queue>
- #include <random>
- class HelloFunctionObject {
- bool stop;
- std::mutex& mutex;
- public:
- HelloFunctionObject(std::mutex& mutex) :stop(false), mutex(mutex) {}
- void operator()() const {
- std::cout << "Hello C++11 from a function object." << std::endl;
- while(getStop());
- std::cout << "Stop C++11 from a function object." << std::endl;
- }
- void setStop(const bool stop) {
- mutex.lock();
- this->stop = stop;
- mutex.unlock();
- }
- bool getStop() const {
- mutex.lock();
- bool rt = stop;
- mutex.unlock();
- return rt;
- }
- };
- class AsynchroniousQueue {
- private:
- std::queue<int> queue_;
- std::mutex block;
- public:
- AsynchroniousQueue();
- void push(const int element);
- int pop();
- size_t size();
- };
- AsynchroniousQueue::AsynchroniousQueue() : block() {}
- void AsynchroniousQueue::push(const int element) {
- block.lock();
- queue_.push(element);
- block.unlock();
- }
- int AsynchroniousQueue::pop() {
- block.lock();
- int rt = queue_.front();
- queue_.pop();
- block.unlock();
- return rt;
- }
- size_t AsynchroniousQueue::size()
- {
- block.lock();
- size_t rt = queue_.size();
- block.unlock();
- return rt;
- }
- int randomInt(int min, int max) {
- static std::random_device rd;
- std::uniform_int_distribution<int> d(min, max);
- return d(rd);
- }
- void asQue(AsynchroniousQueue& queue) {
- for(int i = 0; i < pow(1000, 3); i++) {
- queue.push(randomInt(1, 20));
- }
- }
- int main() {
- /*std::mutex mutex;
- HelloFunctionObject hello_function(mutex);
- std::thread t2(hello_function);
- hello_function.setStop(true);
- t2.join();
- */
- AsynchroniousQueue queue;
- std::thread t1(asQue, queue), t2(asQue, queue);
- t1.join();
- t2.join();
- std::cout << queue.size() << std::endl;
- std::cout << std::endl;
- std::cin.clear();
- std::cin.ignore(2);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement