第一段代码扩展成完整的代码,
#include <chrono>
#include <iostream>
#include <thread>
using namespace std::chrono; // see §35.2
int main() {
auto t0 = high_resolution_clock::now();
std::this_thread::sleep_for(milliseconds{20});
auto t1 = high_resolution_clock::now();
std::cout << duration_cast<nanoseconds>(t1 - t0).count() << " nanoseconds passed\\n";
return 0;
}
之后的生产者和消费者,这是一个简单的生产者和消费者的实现,但是足够用来理解书上的这里的内容了,
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
using namespace std;
class Message { // object to be communicated
// ...
};
queue<Message> mqueue; // the queue of messages
condition_variable mcond; // the variable communicating events
mutex mmutex; // the locking mechanism
void consumer() {
while (true) {
unique_lock<mutex> lck{mmutex}; // acquire mmutex
while (mqueue.empty()) {
mcond.wait(lck); // release lck and wait;
} // re-acquire lck upon wakeup
auto m = mqueue.front(); // get the message
mqueue.pop();
lck.unlock(); // release lck
// ... process m ...
cout << "Consumed a message." << endl;
}
}
void producer() {
while (true) {
Message m;
// ... fill the message ...
unique_lock<mutex> lck{mmutex}; // protect operations
mqueue.push(m);
mcond.notify_one(); // notify
lck.unlock(); // release lock (at end of scope)
cout << "Produced a message." << endl;
this_thread::sleep_for(chrono::seconds(1)); // simulate some delay
}
}
int main() {
thread consumer_thread(consumer);
thread producer_thread(producer);
consumer_thread.join();
producer_thread.join();
return 0;
}