zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    Linux_9/ RAID & LVM
    Linux_8/ fdisk, xfs_quota, edquota
    Linux_7/(chattr, lsattr), (setfacl, getfacl),su
    Linux_6/ Vim, Shell(下),(at, crond), (SUID, SGID, SBIT)
    Linux_5/ Vim, Shell(上)
    Linux_4/ |, (>, 2>, &>, >>, 2>>)
    Map集合的遍历
    List集合三种遍历方法
    MySQL安装
    排序法
  • 原文地址:https://www.cnblogs.com/Fred1987/p/15679422.html
Copyright © 2011-2022 走看看