C++ multi thread via pthread to retrieve returned result
#include <stdio.h>
#include <stdlib.h>
#include <uuid/uuid.h>
#include <unistd.h>
#include <fstream>
#include <istream>
#include <ostream>
#include <sstream>
#include <string.h>
#include <iostream>
#include <chrono>
#include <random>
void retrieveUuid(char *uuidValue) { uuid_t newUUID; uuid_generate(newUUID); uuid_unparse(newUUID, uuidValue); } void *retrieveStruct13(void *structP); void mp14(); int main() { mp14(); return 0; } void mp14() { struct BookStruct arr[100]; pthread_t tdArr[100]; for(int i=0;i<100;i++) { pthread_create(&tdArr[i],NULL,retrieveStruct13,(void*)&arr[i]); pthread_join(tdArr[i],NULL); } for(int i=0;i<100;i++) { printf("Index=%d,Id=%d,Name=%s,Title=%s\n",i,arr[i].BookId,arr[i].BookName,arr[i].BookTitle); free(arr[i].BookName); free(arr[i].BookTitle); } pthread_exit(NULL); } void *retrieveStruct13(void *structP) { struct BookStruct *p; p=(struct BookStruct*)(structP); if(p!=nullptr) { (*p).BookId=rand(); p->BookName=(char*)malloc(40); retrieveUuid(p->BookName); p->BookTitle=(char*)malloc(40); retrieveUuid(p->BookTitle); } return p; }
Compile via below command
g++ -g -std=c++2a -I. h1.cpp -o h1 -luuid -lpthread
Run ./h1
The result is illustrated as below.