pthread_create Linux Explained

In Linux, the pthread_create function is used to create a new thread. The syntax is as follows:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

The meanings of the parameters are as follows:

  1. thread: used for storing the ID of a new thread.
  2. Attribute: Thread attribute, typically set to NULL.
  3. start_routine: The entry function of a thread, which is the starting address where a new thread begins execution.
  4. arg: The argument passed to the start_routine function.

Below is a simple example that demonstrates how to use the pthread_create function to create a new thread.

#include <stdio.h>
#include <pthread.h>

void *myThread(void *arg) {
    int *num = (int *)arg;
    printf("Thread ID: %ld, Number: %d\n", pthread_self(), *num);
    return NULL;
}

int main() {
    pthread_t tid;
    int number = 10;
    
    pthread_create(&tid, NULL, myThread, &number);
    
    pthread_join(tid, NULL);
    
    return 0;
}

In the example above, a thread function named myThread is first defined, then a new thread is created in the main function main using the pthread_create function and parameter number is passed to the new thread. Finally, the pthread_join function is used to wait for the new thread to finish execution.

It is important to note that when creating a new thread using the pthread_create function, you need to link the pthread library. You can compile the program using the following command:

gcc -o myprogram myprogram.c -lpthread
bannerAds