C++ multi thread
//Utility.h #ifndef Utility_H #define Utility_H #include <ctime> #include <iostream> #include <thread> #include <unistd.h> #include <uuid/uuid.h> using namespace std; class Utility { public: static char *uuidValue; static char *dtValue; static void printTimeAndUuid3(int num); static void printUuidAndTime4(int num); static void mt5(int num); Utility(); ~Utility(); char *getTimeNow(); char *getUuid2(); }; #endif
//Utility.cpp #include "Model/Utility.h" char *Utility::dtValue = (char *)malloc(20); char *Utility::uuidValue = (char *)malloc(40); Utility::Utility() { if (Utility::dtValue == NULL) { Utility::dtValue = (char *)malloc(20); cout<<"Utility::dtValue = (char *)malloc(20);"<<endl; } if (Utility::uuidValue == NULL) { Utility::uuidValue = (char *)malloc(40); cout<<"Utility::uuidValue = (char *)malloc(40);"<<endl; } cout << "Constructor Utility::Utility() and now is " << getTimeNow() << endl; } Utility::~Utility() { if (Utility::uuidValue != NULL) { free(Utility::uuidValue); Utility::uuidValue = NULL; } if (Utility::dtValue != NULL) { cout << "Deconstructor Utility::~Utility() and now is " << getTimeNow() << endl; free(Utility::dtValue); Utility::dtValue = NULL; } } char *Utility::getTimeNow() { time_t rawTime = time(NULL); struct tm tmInfo = *localtime(&rawTime); strftime(dtValue, 20, "%Y%m%d%H%M%S", &tmInfo); return dtValue; } char *Utility::getUuid2() { uuid_t newUUID; uuid_generate(newUUID); uuid_unparse(newUUID, uuidValue); return uuidValue; } void Utility::printTimeAndUuid3(int num) { Utility ul; for (int i = 0; i < num; i++) { cout << "T= " << ul.getTimeNow() << "," << ul.getUuid2() << endl; usleep(100000); } } void Utility::printUuidAndTime4(int num) { Utility ul; for (int i = 0; i < num; i++) { cout << "U= " << ul.getUuid2() << "," << ul.getTimeNow() << endl; usleep(100000); } } void Utility::mt5(int num) { thread t1(printTimeAndUuid3, num); t1.join(); thread t2(printUuidAndTime4, num); t2.join(); }
#include "Model/Utility.h" void mt64(int num); int main(int args, char *argv[]) { try { mt64(atoi(argv[1])); } catch (const std::exception &e) { std::cerr << e.what() << '\n'; } return 0; } void mt64(int num) { Utility::mt5(num); }