24

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

pthread_t cThread;
if(pthread_create(&cThread, NULL, work, param)){
    perror("ERROR creating thread.");
}

However I need to make another function that goes into 'work' and 'param' variable as parameters of create function. My friend told me that I just need to put any code in the work function that loops infinitely so the thread does not die.. Can anyone explain each parameter goes in to the pthread_create function- especially for work and param? I searched Google for this, but most of tutorials are so hard to understand the concept...

Leanne
  • 667
  • 3
  • 11
  • 23

2 Answers2

44

The four parameters to pthread_create are, in order:

  1. A pointer to a pthread_t structure, which pthread_create will fill out with information on the thread it creates.

  2. A pointer to a pthread_attr_t with parameters for the thread. You can safely just pass NULL most of the time.

  3. A function to run in the thread. The function must return void * and take a void * argument, which you may use however you see fit. (For instance, if you're starting multiple threads with the same function, you can use this parameter to distinguish them.)

  4. The void * that you want to start up the thread with. Pass NULL if you don't need it.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
25

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.

Foo Bah
  • 25,660
  • 5
  • 55
  • 79
  • 7
    Please don't cast return values from `malloc`. Its return is `void*` and is always assignable to any data pointer. Same goes for `parm`. – Jens Gustedt Aug 09 '11 at 06:19
  • 2
    @Jens If you are using C++, then you **must** explicitly cast return values from `malloc`, or the code won't compile. If you are using C, then it is optional. – lingjiankong Aug 31 '19 at 07:31