C , how to create thread using pthread_create function

前端 未结 2 647
北恋
北恋 2021-02-01 18:39

I\'m making a c file for a dispatch queue that gets a task and put it in to a queue which is the linked list. In order to do this, I need to create threads using



        
2条回答
  •  借酒劲吻你
    2021-02-01 19:07

    clarifying duskwuff's answer:

    work parameter is a function pointer. The function should take one argument which is indicated as type void * and return value void *.

    param is expected to be a pointer to the data that work will receive.

    As an example, lets say you want to pass two int to the worker. Then, you can create something like this:

    int *param = (int *)malloc(2 * sizeof(int));
    param[0] = 123;
    param[1] = 456;
    pthread_create(&cThread, NULL, work, param);
    

    Then your work function can convert the pointer type and grab the param data:

    void *work(void * parm) {
        int *param = (int *)parm;
        int first_val = param[0];
        ....
    }
    

    You can do more complex stuff, like creating a struct with all of the data you need to pass.

提交回复
热议问题