C pthread pass struct parameter

#include <stdio.h>
#include <stdlib.h>
#include <uuid/uuid.h>
#include <string.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>

struct BookStrut
{
    int BookId;
    char *BookAuthor;
    char *BookISBN;
};

void retrieveUuidVia(char *uuidValue);
void* printStruct13(void *ptr);
void pthread14();

int main()
{
    pthread14();
    return 0;
}

void pthread14()
{
    pthread_t t1;
    int ret1;
    struct BookStrut bs;
    bs.BookId=2022;
    bs.BookAuthor=(char*)malloc(40);
    retrieveUuidVia(bs.BookAuthor);
    bs.BookISBN=(char*)malloc(40);
    retrieveUuidVia(bs.BookISBN);
    struct BookStrut *sp=&bs;
    ret1=pthread_create(&t1,NULL,printStruct13,(void*)sp);   
    pthread_join(t1,NULL);
    exit(0); 
}

void* printStruct13(void *ptr)
{ 
    struct BookStrut *bsp=(struct BookStrut*)ptr;
    printf("BookId=%d,Author=%s,ISBN=%s\n",bsp->BookId,bsp->BookAuthor,bsp->BookISBN);
    free(bsp->BookAuthor);
    free(bsp->BookISBN);
}

void retrieveUuidVia(char *uuidValue)
{
    uuid_t newuUID;
    uuid_generate(newuUID);
    uuid_unparse(newuUID,uuidValue);
}

struct BookStrut bs;
bs.BookId=2022;
bs.BookAuthor=(char*)malloc(40);
retrieveUuidVia(bs.BookAuthor);
bs.BookISBN=(char*)malloc(40);
retrieveUuidVia(bs.BookISBN);
struct BookStrut *sp=&bs;

When pass struct as parameter,at first retrieve struct pointer as below;

struct BookStrut *sp=&bs;

Then pass as the (void)*sp format as below

ret1=pthread_create(&t1,NULL,printStruct13,(void*)sp).

Also you should pay attention to the convert void pointer to the specified type as below.

 struct BookStrut *bsp=(struct BookStrut*)ptr;

原文地址:https://www.cnblogs.com/Fred1987/p/15606362.html