[Linux] Thread overview, creating threads, terminating threads

orange color

Thread overview

Similar to processes, threads are a mechanism that allows an application to perform multiple tasks concurrently. A process can contain multiple threads.

A process is the smallest unit for CPU allocation of resources, and a thread is the smallest unit for scheduling execution by the operating system.

Threads are lightweight processes (LWP: Light Wight Process). In the Linux environment, the essence of threads is still processes.

View the LWP number of the specified process:ps -Lf pid

Information between processes is difficult to share and process communication is difficult; the cost of calling fork() to create a process is relatively high. Threads solve these problems through sharing.

Shared and non-shared resources between threads

  • Shared resources: process ID and parent process ID, process group ID and session ID, user ID and user group ID, file descriptor, signal processing, file system related information, virtual address space (except stack and .text).
  • Non-shared resources: thread ID, signal mask, thread-specific data, error variables, real-time scheduling strategy and priority, stack, local variables and function call link information

Check the current pthread library version:getconf GNU_LIBPTHREAD_VERSION

1. Create a thread

Function analysis

/*
    一般情况下,main函数所在的线程我们称之为主线程(main线程),其余创建的线程
    称之为子线程。
    程序中默认只有一个进程,fork()函数调用,2进行
    程序中默认只有一个线程,pthread_create()函数调用,2个线程。

    #include <pthread.h>
    int pthread_create(pthread_t *thread, const pthread_attr_t *attr, 
    void *(*start_routine) (void *), void *arg);

        - 功能:创建一个子线程
        - 参数:
            - thread:传出参数,线程创建成功后,子线程的线程ID被写到该变量中。
            - attr : 设置线程的属性,一般使用默认值,NULL
            - start_routine : 函数指针,这个函数是子线程需要处理的逻辑代码
            - arg : 给第三个参数使用,传参
        - 返回值:
            成功:0
            失败:返回错误号。这个错误号和之前errno不太一样。
            获取错误号的信息:  char * strerror(int errnum);

*/

Code example

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

void * callback(void * arg) {
    
    
    printf("child thread...\n");
    printf("arg value: %d\n", *(int *)arg);
    return NULL;
}

int main() {
    
    

    pthread_t tid;

    int num = 10;

    // 创建一个子线程
    int ret = pthread_create(&tid, NULL, callback, (void *)&num);

    if(ret != 0) {
    
    
        char * errstr = strerror(ret);
        printf("error : %s\n", errstr);
    } 

    for(int i = 0; i < 5; i++) {
    
    
        printf("%d\n", i);
    }

    sleep(1);

    return 0;   // exit(0);
}

Compile and run the program (note that compilation requires its dynamic library, otherwise an error will be reported. You can review the contents of the previous dynamic library and static library). The results are as follows: the entire main function is the content of the main thread,
Insert image description here
and the callback function is the content of other threads. If you want to create more threads, continue int ret = pthread_create(&tid, NULL, callback, (void *)&num);. The content in the new thread can be callback or itself Pass it in when creating a new function.

2. Terminate the thread

Function analysis

/*

    #include <pthread.h>
    void pthread_exit(void *retval);
        功能:终止一个线程,在哪个线程中调用,就表示终止哪个线程
        参数:
            retval:需要传递一个指针,作为一个返回值,可以在pthread_join()中获取到。

    pthread_t pthread_self(void);
        功能:获取当前的线程的线程ID

    int pthread_equal(pthread_t t1, pthread_t t2);
        功能:比较两个线程ID是否相等
        不同的操作系统,pthread_t类型的实现不一样,有的是无符号的长整型,有的
        是使用结构体去实现的。所以需要调用该函数,而不是直接用"="来进行比较
*/

Code example

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

void * callback(void * arg) {
    
    
    //获取当前线程的id
    printf("child thread id : %ld\n", pthread_self());
    return NULL;    // pthread_exit(NULL);
} 

int main() {
    
    

    // 创建一个子线程
    pthread_t tid;
    int ret = pthread_create(&tid, NULL, callback, NULL);

    if(ret != 0) {
    
    
        char * errstr = strerror(ret);
        printf("error : %s\n", errstr);
    }

    // 主线程
    for(int i = 0; i < 5; i++) {
    
    
        printf("%d\n", i);
    }

    printf("tid : %ld, main thread id : %ld\n", tid ,pthread_self());

    // 让主线程退出,当主线程退出时,不会影响其他正常运行的线程。
    pthread_exit(NULL);

    printf("main thread exit\n");

    return 0;   // exit(0);
}

It can be seen that after pthread_exit(NULL)execution, the main thread has exited, so the subsequent ones printf("main thread exit\n")will not be executed. In the results, I did not see main thread exitthis sentence printed out
Insert image description here

Guess you like

Origin blog.csdn.net/mhyasadj/article/details/130898568