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;

  • 相关阅读:
    以JPanel为基础实现一个图像框
    扩展JButton实现自己的图片按钮
    箴言录2014年4月22日
    搜集整理一些Cron表达式例子
    长途旅行感悟
    箴言录2014年4月19日
    Linux下显示硬盘空间的两个命令
    Linux命令复习和练习_02
    Dash:程序员的的好帮手
    Linux的桌面环境gnome、kde、xfce、lxde 等等使用比较
  • 原文地址:https://www.cnblogs.com/Fred1987/p/15606362.html
Copyright © 2011-2022 走看看