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;

  • 相关阅读:
    java 23种设计模式 深入理解
    ORACLE 一条记录 某字段值以';'拆分为多条记录
    rabbitmq集群故障恢复
    ORACLE 时间加减操作
    Asp.net MVC Razor输出字符串方法(js中嵌入razor)
    C# ToString() 数据格式
    DOM的整个知识体系
    EF 连接模式
    EF Code First 数据库连接方式
    使用border实现提示框的
  • 原文地址:https://www.cnblogs.com/Fred1987/p/15606362.html
Copyright © 2011-2022 走看看