• 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

  • 相关阅读:
    【node.js】GET/POST请求、Web 模块
    【node.js】全局变量、常用工具、文件系统
    【node.js】函数、路由
    【node.js】模块系统、函数
    【node.js】Stream(流)
    跨域问题的产生,怎么解决它?
    array.splice()
    数组的方法
    js跨域请求的5中解决方式
    3分钟看懂flex布局
  • 原文地址:https://www.cnblogs.com/Fred1987/p/15733650.html
Copyright © 2020-2023  润新知