#include <atomic> #include <chrono> #include <cmath> #include <condition_variable> #include <cstddef> #include <forward_list> #include <fstream> #include <functional> #include <future> #include <iomanip> #include <iostream> #include <latch> #include <list> #include <map> #include <memory> #include <mutex> #include <optional> #include <queue> #include <random> #include <stack> #include <string> #include <thread> #include <utility> #include <uuid/uuid.h> #include <vector> char *uuid_value = (char *)malloc(40); char *get_uuid_value() { uuid_t new_uuid; uuid_generate(new_uuid); uuid_unparse(new_uuid, uuid_value); return uuid_value; } std::string get_time_now(bool is_exact = true) { std::stringstream ss; std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now(); time_t raw_time = std::chrono::high_resolution_clock::to_time_t(now); struct tm tm_info = *localtime(&raw_time); ss << std::put_time(&tm_info, "%Y%m%d%H%M%S"); if (is_exact) { std::chrono::seconds seconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()); std::chrono::milliseconds mills = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()); std::chrono::microseconds micros = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()); std::chrono::nanoseconds nanos = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()); ss << "_" << std::setw(3) << std::setfill('0') << (mills.count() - seconds.count() * 1000) << std::setw(3) << std::setfill('0') << (micros.count() - mills.count() * 1000) << std::setw(3) << std::setfill('0') << (nanos.count() - micros.count() * 1000); } return ss.str(); } std::mutex _write_mtx; void write_num(std::uint64_t num, const std::string &file_name = "log.txt") { std::lock_guard<std::mutex> _lock_guard(_write_mtx); std::fstream w_file(file_name, std::ios::out); w_file << num << std::endl; w_file.close(); } std::uint64_t read_num(const std::string &file_name = "log.txt") { std::lock_guard<std::mutex> _lock_guard(_write_mtx); std::uint64_t num = 0; std::fstream r_file(file_name, std::ios::in); std::string line; getline(r_file, line); if (line != "") { num = std::stoll(line); } return num; } void print_num() { static std::uint64_t num = 0; while (1) { num = read_num(); std::cout << ++num<<",thread id:"<<std::this_thread::get_id()<<","<<get_time_now()<< std::endl; write_num(num); std::this_thread::sleep_for(std::chrono::seconds(1)); } } int main(int agrs, char **argv) { print_num(); std::cout << get_time_now() << ",thread id:" << std::this_thread::get_id() << ",finished in " << __FUNCTION__ << std::endl; }
Compile
g++-12 -std=c++2a -I. *.cpp -o h1 -luuid -lpthread
标签:std,multi,via,uuid,chrono,better,file,time,include From: https://www.cnblogs.com/Fred1987/p/17486251.html