• 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;

  • 相关阅读:
    Android中手机录屏并转换GIF的两种方式
    Android中访问sdcard路径的几种方式
    Android中开发工具Android Studio修改created用户(windows环境)
    [UOJ211][UER #6]逃跑
    [CF1168D]Anagram Paths
    [CF852H]Bob and stages
    Codechef BINOMSUM
    [ZJOI2019]开关
    [CF1161F]Zigzag Game
    [CF1149E]Election Promises
  • 原文地址:https://www.cnblogs.com/Fred1987/p/15606362.html
Copyright © 2020-2023  润新知