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

  • 相关阅读:
    海尔大数据精准营销平台(内部资料)
    马化腾做的PPT:产品设计与用户体验
    网站上线后,第一次完成线上线下整个环节
    灵感不断
    redis命令
    Redis持久化实践及灾难恢复模拟
    [转]创业公司常见的25个法律问题
    用python语言编写网络爬虫
    Python3常用网络编程模块介绍
    Python3数据库模块(sqlite3,SQLite3)
  • 原文地址:https://www.cnblogs.com/Fred1987/p/15606362.html
Copyright © 2011-2022 走看看