[Linux operating system] Thread operation in Linux system programming, pthread_exit, pthread_join, pthread_cancel, pthread_detach...

Multithreaded programming has become a common technique in modern computer systems. Multi-threaded programming can make full use of the computer's multi-core processors to improve the concurrency and performance of the program. In the Linux system, a series of thread operation functions are provided for creating, managing and controlling threads. This article will introduce the commonly used thread operation functions in Linux system programming, including pthread_exit, pthread_join, pthread_cancel and pthread_detach. By learning the usage of these functions, we can better understand and master the skills of multi-threaded programming, and improve the efficiency and reliability of the program.

insert image description here


introduce

In Linux system programming, a thread is a lightweight execution unit that shares the same address space with a process and can execute tasks concurrently. Thread operations are some functions commonly used in multi-threaded programming, including pthread_exit, pthread_join, pthread_canceland pthread_detachand so on. This article will introduce the usage and characteristics of these functions in detail.


1. pthread_exit function

effect:

pthread_exitThe function is used for the exit of the thread, it can be called anywhere, so that the thread ends execution early.

prototype:

void pthread_exit(void *retval);

Parameters and return values:

Among them, retvalis the return value of the thread, which can be any type of pointer. pthread_exit()A thread terminates its own execution by calling a function, which is retvalpassed as a return value to the parent thread or threads waiting for it.

Example usage:

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

void *thread_func(void *arg) {
    
    
    int value = *(int *)arg;
    printf("Thread value: %d\n", value);
    pthread_exit(NULL);
}

int main() {
    
    
    pthread_t tid;
    int value = 10;
    pthread_create(&tid, NULL, thread_func, &value);
    pthread_join(tid, NULL);
    printf("Main thread exit\n");
    return 0;
}

In the above example, pthread_createa new thread is created by a function, and an integer value is passed to the thread function thread_func. The integer value is printed in the thread function, and pthread_exitthe thread is exited through the function. In the main thread, pthread_joinwait for the child thread to end through the function.


2. pthread_join function

effect:

pthread_join()The function is used to wait for the end of a thread and get the return value of the thread. It can block the calling thread until the waited thread finishes.

prototype:

int pthread_join(pthread_t thread, void **retval);

parameter:

  • thread: The identifier of the thread to wait on.
  • retval: A pointer to a pointer to receive the thread's return value.

return value:

  • On success, returns 0.
  • On failure, an error code is returned.

Example:

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

void *thread_func(void *arg) {
    
    
    int *value = (int *)arg;
    printf("Thread value: %d\n", *value);
    *value = *value * 2;
    pthread_exit(NULL);
}

int main() {
    
    
    pthread_t tid;
    int value = 10;
    pthread_create(&tid, NULL, thread_func, (void *)&value);
    pthread_join(tid, NULL);
    printf("Main value: %d\n", value);
    return 0;
}

In the above example, the main thread creates a new thread and passes an integer value of 10 as a parameter. The new thread's thread function thread_funcwill print the received parameter value, multiply it by 2 and exit. The main thread calls pthread_join()the function to wait for the end of the new thread and obtain its return value. Finally, the main thread prints the received parameter value and outputs the value multiplied by 2.

explain:

  • The main thread creates a new thread and passes it an integer value of 10 as a parameter.
  • The new thread's thread function thread_funcreceives the parameter value 10 and prints it out.
  • The thread function multiplies the parameter value by 2 and pthread_exit()exits through the function.
  • The main thread calls pthread_join()the function to wait for the end of the new thread.
  • The main thread gets the new thread's return value, but it's not used here, so NULL is passed.
  • The main thread prints the received parameter value 10 and outputs the value 20 multiplied by 2.
  • The program ends.

Through pthread_join()the function, the main thread can wait for the end of the child thread and obtain its return value, so as to realize the synchronization and data exchange between threads.


3. pthread_cancel function

effect:

pthread_cancel()Function used to cancel the execution of a thread. It sends a cancellation request to the specified thread, but does not guarantee that the thread will terminate immediately.

prototype:

int pthread_cancel(pthread_t thread);

parameter:

  • thread: The identifier of the thread to cancel.

return value:

  • On success, returns 0.
  • On failure, an error code is returned.

Example:

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

void *thread_func(void *arg) {
    
    
    int i;
    for (i = 0; i < 5; i++) {
    
    
        printf("Thread: %d\n", i);
        sleep(1);
    }
    pthread_exit(NULL);
}

int main() {
    
    
    pthread_t tid;
    pthread_create(&tid, NULL, thread_func, NULL);
    sleep(3);
    pthread_cancel(tid);
    pthread_join(tid, NULL);
    printf("Thread cancelled\n");
    return 0;
}

In the above example, the main thread creates a new thread, and the thread function of the new thread thread_funcwill print a number every 1 second, and print 5 times in total. After the main thread waits for 3 seconds, it calls pthread_cancel()the function to cancel the execution of the new thread. Then, the main thread calls pthread_join() to wait for the new thread to finish, and print out a message that the thread was cancelled.

explain:

  • The main thread creates a new thread and calls pthread_create()the function.
  • The new thread's thread function thread_funcwill print a number every 1 second, for a total of 5 prints.
  • After the main thread waits for 3 seconds, call pthread_cancel()the function to cancel the execution of the new thread.
  • The main thread calls pthread_join()the function to wait for the end of the new thread.
  • After the new thread is canceled, the main thread prints out the message that the thread was cancelled.
  • The program ends.

Through pthread_cancel()the function, you can send a cancellation request to the specified thread, but it does not guarantee that the thread will terminate immediately. Canceled threads need to check for cancellation requests in place and clean up as necessary.


4. pthread_detach function

effect:

pthread_detach()The function is used to set a thread to the detached state, so that it automatically releases resources when it terminates, without requiring other threads to call the pthread_join()function to wait for it to end.

prototype:

int pthread_detach(pthread_t thread);

parameter:

  • thread: The identifier of the thread to set to detached state.

return value:

  • On success, returns 0.
  • On failure, an error code is returned.

Example:

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

void *thread_func(void *arg) {
    
    
    printf("Thread started\n");
    sleep(2);
    printf("Thread finished\n");
    pthread_exit(NULL);
}

int main() {
    
    
    pthread_t tid;
    pthread_create(&tid, NULL, thread_func, NULL);
    pthread_detach(tid);
    sleep(3);
    printf("Main thread finished\n");
    return 0;
}

In the above example, the main thread creates a new thread and calls pthread_create()the function. The new thread's thread function thread_funcprints a message at the start, then sleeps for 2 seconds and then prints another message. After the main thread creates a new thread, it calls pthread_detach()the function to set it to the detached state. Then, the main thread sleeps for 3 seconds, prints a message, and ends.

explain:

  • The main thread creates a new thread and calls pthread_create()the function.
  • The thread function for a new thread thread_funcprints a message when it starts.
  • The main thread calls pthread_detach()the function to set the new thread to the detached state.
  • Print a message after the new thread sleeps for 2 seconds.
  • Print a message after the main thread sleeps for 3 seconds.
  • The program ends.

Through pthread_detach()the function, a thread can be set to detached state, so that it automatically releases resources when it terminates, without requiring other threads to call pthread_join()functions to wait for it to end. This is useful for situations where you don't need to wait for the thread to end.


Summarize

This article introduces the thread operation functions in Linux system programming, including pthread_exit, pthread_join, pthread_canceland pthread_detach. These functions provide the control and management of threads, and can realize functions such as thread exit, wait, cancel and separation. Proficiency in the usage of these functions is very important for multi-threaded programming.

Guess you like

Origin blog.csdn.net/Goforyouqp/article/details/132393938