|
- #include <iostream>
- #include <thread>
- #include <functional>
- #include <mutex>
- #include <condition_variable>
- using namespace std::placeholders;
- class Application
- {
- std::mutex m_mutex;
- std::condition_variable m_condVar;
- bool m_bDataLoaded;
- public:
- Application()
- {
- m_bDataLoaded = false;
- }
- void loadData()
- {
- std::cout<<"loadData start"<<std::endl;
- // Make This Thread sleep for 1 Second
- std::this_thread::sleep_for(std::chrono::milliseconds(1000));
- std::cout<<"Loading Data from XML"<<std::endl;
- // Lock The Data structure
- std::lock_guard<std::mutex> guard(m_mutex);
- // Set the flag to true, means data is loaded
- m_bDataLoaded = true;
- // Notify the condition variable
- m_condVar.notify_one();//通知另一个线程去检查m_bDataLoaded是否为真
- }
- bool isDataLoaded()
- {
- if (m_bDataLoaded) {
- std::cout << "load true" << std::endl;
- } else {
- std::cout << "load false" << std::endl;
- }
- return m_bDataLoaded;
- }
- void mainTask()
- {
- std::cout<<"Do Some Handshaking"<<std::endl;
- // Acquire the lock
- std::unique_lock<std::mutex> mlock(m_mutex);
- // Start waiting for the Condition Variable to get signaled
- // Wait() will internally release the lock and make the thread to block
- // As soon as condition variable get signaled, resume the thread and
- // again acquire the lock. Then check if condition is met or not
- // If condition is met then continue else again go in wait.
- m_condVar.wait(mlock, std::bind(&Application::isDataLoaded, this));//检查m_bDataLoaded是否为真,为真则线程向下执行,为假则阻塞线程并暂时释放锁(释放锁其它线程才可以顺利使用资源)
- std::cout<<"Do Processing On loaded Data"<<std::endl;
- }
- };
- int main()
- {
- Application app;
- std::thread thread_1(&Application::mainTask, &app);
- std::thread thread_2(&Application::loadData, &app);
- thread_1.join();
- thread_2.join();
- return 0;
- }
- /*输出结果
- Do Some Handshaking
- load false
- loadData start
- Loading Data from XML
- load true
- Do Processing On loaded Data
- */
复制代码
|
|