I have simple demo app for this. I use ctime
for get timestamp std::time(0)
. this code should not be reused, it use simple queue (not thread-safe) just for make it simple demo.
#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;
}
Producer thread produce some integer to queue
, then wait for random second [0-5]. Then the consumer thread, wait for queue
filled. When queue
filled, it consume (queue.pop()
) and print to screen with its unix timestamp (seconds since 01-Jan-1970).
it will produce something like this:
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.