How to pass multiple parameters to a thread in C

前端 未结 2 631
一向
一向 2020-12-06 06:21

I am trying to pass two parameters to a thread in C. I have created an array (of size 2) and am trying to pass that array into the thread. Is this the right approach of pass

相关标签:
2条回答
  • 2020-12-06 06:30

    Since you pass in a void pointer, it can point to anything, including a structure, as per the following example:

    typedef struct s_xyzzy {
        int num;
        char name[20];
        float secret;
    } xyzzy;
    
    xyzzy plugh;
    plugh.num = 42;
    strcpy (plugh.name, "paxdiablo");
    plugh.secret = 3.141592653589;
    
    status = pthread_create (&server_thread, NULL, disk_access, &plugh);
    // pthread_join down here somewhere to ensure plugh
    //   stay in scope while server_thread is using it.
    
    0 讨论(0)
  • 2020-12-06 06:56

    That's one way. The other usual one is to pass a pointer to a struct. This way you can have different "parameter" types, and the parameters are named rather than indexed which can make the code a bit easier to read/follow sometimes.

    0 讨论(0)
提交回复
热议问题