Passing Parameters to pthread_create in Linux

When creating a thread in Linux with pthread_create, you can pass parameters to the thread by passing a void pointer parameter. The specific steps are as follows:

  1. Define a structure that includes the parameters needed to be passed to the thread.
#include <stdio.h>

typedef struct {
    int a;
    char b;
} ThreadArgs;
  1. Create a structure and initialize its parameters in the main thread, then pass the address of the structure as a parameter to the pthread_create function.
int main() {
    pthread_t thread_id;
    ThreadArgs args;

    args.a = 10;
    args.b = 'A';

    pthread_create(&thread_id, NULL, myThreadFunction, &args);

    // 等待线程结束
    pthread_join(thread_id, NULL);

    return 0;
}
  1. In the newly created thread function, cast the passed parameter to the type ThreadArgs and access its arguments.
void* myThreadFunction(void* arg) {
    ThreadArgs *args = (ThreadArgs*)arg;

    printf("Parameter a: %d\n", args->a);
    printf("Parameter b: %c\n", args->b);

    return NULL;
}

In this way, it is easy to pass parameters to a thread when creating it.

bannerAds