I have a adream
阿新 • • 發佈:2018-12-20
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <chrono>
std::vector<int> global_queue;
std::mutex global_mutex;
std::condition_variable global_queue_cv;
int get_from_queue ()
{
std::unique_lock<std::mutex> lock(global_mutex);
std::cout << "get_from_queue: before loop, is_locked " << lock.owns_lock() << std::endl;
while (global_queue.empty())
{
global_queue_cv.wait(lock);
std::cout << "get_from_queue: inloop, is_locked " << lock.owns_lock() << std::endl;
}
std::cout << "get_from_queue: fater wait, is_locked " << lock.owns_lock() << std::endl;
auto v = global_queue.back();
global_queue.pop_back();
return v;
}
void put_in_queue(int v)
{
std::unique_lock<std::mutex> lock(global_mutex);
std::cout << "put_in_queue: is_locked " << lock.owns_lock() << std::endl;
global_queue.push_back(v);
global_queue_cv.notify_all();
std::cout << "put_in_queue: after notify_all, is_locked " << lock.owns_lock() << std::endl;
}
void get_thread()
{
for (int i = 0; i < 10; ++i)
{
auto v = get_from_queue();
std::cout << "get_thread : v = " << v << std::endl << std::endl << std::endl<< std::endl;
}
}
void put_thread()
{
for (int i = 0; i < 10; ++i)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
int v = i + 100;
put_in_queue(v);
std::cout << "put_thread : v = " << v << std::endl << std::endl << std::endl<< std::endl;
}
}
int main()
{
std::thread work_get(get_thread);
std::thread work_put(put_thread);
work_get.join();
work_put.join();
return 0;
}