• 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

  • 相关阅读:
    支付宝API
    三级联动
    高精尖面试题(七)
    高精尖面试题(六)
    高精尖面试题(五)
    第十二章、使用继承
    第十章、使用数组
    第十一章、理解参数数组
    第九章、使用枚举和结构创建值类型
    第八章、理解值类型和引用
  • 原文地址:https://www.cnblogs.com/Fred1987/p/15733650.html
Copyright © 2020-2023  润新知