C++ multi thread via pthread to retrieve returned result

2021/12/12 17:49:26

本文主要是介绍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.

 



这篇关于C++ multi thread via pthread to retrieve returned result的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程