У меня есть простое демонстрационное приложение для этого.Я использую ctime
для получения метки времени std::time(0)
. этот код не должен использоваться повторно, он использует простую очередь (не ориентированную на многопотоковое исполнение) только для упрощения демонстрации.
#include <iostream> // std::cout
#include <thread> // std::thread
#include <cstdio> // printf, scanf, puts, NULL
#include <cstdlib> // srand, rand
#include <ctime> // time
#include <chrono> // std::chrono::seconds, std::this_thread::sleep_for
#include <queue> // std::ueue
std::queue<int> queue;
void producer() {
srand(time(NULL));
while (1) {
int message = rand();
queue.push(message);
int sleep = rand() % 5;
std::this_thread::sleep_for(std::chrono::seconds(sleep));
}
}
void consumer()
{
int start_time = std::time(0);
while(1) {
printf("waiting\n");
while (queue.empty()); // busy waiting
int timestamp = std::time(0);
int message = queue.front();
int arrival_time_from_start = (timestamp - start_time);
queue.pop();
printf("message %d arrive at %d (unix timestamp), %d second after app start.\n", message, timestamp, arrival_time_from_start);
}
}
int main()
{
std::thread first(producer);
std::thread second(consumer);
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes
return 0;
}
Поток производителя выдает некоторое целое число в queue
, затемдождитесь случайной секунды [0-5].Затем потребительская нить, дождитесь заполнения queue
.Когда queue
заполнено, оно потребляет (queue.pop()
) и печатает на экране со своей меткой времени Unix (секунды с 01 января 1970 года).
будет производить что-то вроде этого:
waiting
message 1611033160 arrive at 1527496314 (unix timestamp), 0 second after app start.
waiting
message 1055908354 arrive at 1527496318 (unix timestamp), 4 second after app start.
waiting
message 788236843 arrive at 1527496320 (unix timestamp), 6 second after app start.
waiting
message 1849353197 arrive at 1527496323 (unix timestamp), 9 second after app start.
waiting
message 62004690 arrive at 1527496326 (unix timestamp), 12 second after app start.
waiting
message 1668815337 arrive at 1527496326 (unix timestamp), 12 second after app start.
waiting
message 533376047 arrive at 1527496330 (unix timestamp), 16 second after app start.