C++ multithread via pthread

#include <iostream>
#include <uuid/uuid.h>
#include <ctime>
#include <string>
#include <sstream>
#include <unistd.h>
#include <fstream>
#include <pthread.h>  

using namespace std;

static char *uuidValue = (char *)malloc(40);
static char *dtValue = (char *)malloc(20);
char *getUuidValue1();
char *getTimeNow(); 
struct BookStruct
{
    int BookId;
    string BookName;
    string BookTitle;
};


char *getTimeNow()
{
    time_t rawTime = time(NULL);
    struct tm tmInfo = *localtime(&rawTime);
    strftime(dtValue, 20, "%Y%m%d%H%M%S", &tmInfo);
    return dtValue;
}

char *getUuidValue1()
{
    uuid_t newUUID;
    uuid_generate(newUUID);
    uuid_unparse(newUUID, uuidValue);
    return uuidValue;
}


void *printBookStruct(void *p);
void mt12();
 
int main()
{
    mt12();
    return 0;
}

void mt12()
{
    struct BookStruct arr[100];
    for(int i=0;i<100;i++)
    {
        arr[i].BookId=i*i*i*i;
        arr[i].BookName=getUuidValue1();
        arr[i].BookTitle=getUuidValue1();
    }

    pthread_t tArr[100];
    int res;
    for(int i=0;i<100;i++)
    {
        void *vp=&arr[i]; 
        res=pthread_create(&tArr[i],NULL,&printBookStruct,vp);
        pthread_join(tArr[i],NULL);
    }
    cout<<"Finished in mt12() and now is "<<getTimeNow()<<endl;
}

void *printBookStruct(void *p)
{
    struct BookStruct *sp=(struct BookStruct*)(p);
    if(sp!=nullptr)
    {
        cout<<"Id="<<sp->BookId<<",name="<<sp->BookName<<",title="<<sp->BookTitle<<endl;
    }
    return nullptr;
}

Compile via g++

g++ -g -std=c++2a -I. h1.cpp -lpthread -o h1  -luuid

Run as ./h1

C++ multithread via pthread

 

上一篇:CPS fact debug - Continuation-pass style


下一篇:CLR via C# 基类构造函数调用继承类的override method疑问