20155321 "Information security system Design" Linux multi-Threading in-depth learning

Source: Internet
Author: User

Re-learning of the basic concepts of multi-process learning
    • A thread is the smallest unit of program execution (a process is the smallest unit of resource management), and a thread belongs to a process
    • The process has its own data segments, code snippets, and stack segments. Threads are often called lightweight processes, and each thread shares all of the resources of its affiliated processes, including open files, memory pages, signal identities, and dynamically allocated memory.

    • Threads are smaller than processes, so threads spend less CPU resources
    • In the case of large concurrency and constant client requests on the server side, the service side should use the thread
    • When the process exits, the threads generated by the process are forced to exit and clear. A process requires at least one thread (main thread) as its instruction executor, a process that manages resources, assigns threads to a CPU to execute

    • Classification of threads
    • User-level threads (determined by the user, primarily to resolve context switching issues) and kernel-level threads (implemented by the kernel scheduling mechanism)
    • User-level thread-bound kernel-level threads run, kernel-level threads in a process are allocated to fixed time slices, and user-level threads allocate time slices based on kernel-level threads
    • When the CPU is allocated to the thread after the time slice is exhausted but the thread is not finished, the thread will return from the running state to the ready state, the CPU to other threads to use

    • In Linux, the general use of Pthread line libraries implementation of thread access and control, so at compile time to link the library pthread, that is-lpthread

    • The identity of the thread
    • Each thread has its own unique identity (identity is the pthread_t data type)
    • Thread identity only works in the process environment in which it belongs
    • + + functions related to thread ID + +: int pthread_equal(pthread_t,pthread_t) : Determine thread consistency; pthread_t pthread_self(void) : Get the calling thread's own ID

Understanding problems encountered in learning
    • Issue 1: For the CPU, each time a process is taken to the CPU, and the process runs essentially refers to the threads in the process are running. But there are multiple threads in a process (including the main thread and several sub-threads created by the main thread to satisfy the customer's needs), and at some point, which of these threads gets the CPU running?
    • Depending on the information on the web, the specific thread that gets the CPU and executes the scheduling that needs to pass through the system, such as scheduling a thread from the ready state to the running State based on the priority of those threads. that is, the system first dispatches a process to the running state, and then dispatches a thread to the running State based on certain rules, such as the priority and scheduling algorithms mentioned in the operating system class. (Of course, these threads will also be based on an algorithm to switch, when the process has a lot of threads, it is generally difficult for a thread to occupy the CPU)
    • Issue 2: The user-level thread and the kernel-level thread are in a bind-run state, which means that the user-level thread is running after the kernel-level thread. So the following is not the case: a kernel-level thread is bound to multiple user-level threads, and when this kernel-level thread is dispatched, multiple user-level threads bound to it are dispatched, so that it does not cause any CPU confusion? (that is, how does the CPU know which thread to execute?)
    • By default, a user-level thread and a kernel-level thread are one-to-another, such as a kernel-level thread that is allowed to execute 10ns, and the user-level thread that it binds to executes 10ns of time. Although can be more to one, but will lead to poor real-time
Creation of Threads
    • Call function: int pthread_create (pthread_t *restrict tidp,const pthread_attr_t *restrict attr,void * (*START_RTN) (void*), void *restrict arg); Success returns 0
    • TIDP: Thread identifier pointer
    • attr: Thread property pointer (not required)
    • START_RTN: The starting address of the thread running function (requires user-defined)
    • ARG: argument passed to the thread run function
    • new creation thread runs from the address of the START_RTN function
    • Does not guarantee the execution order of the new thread and the calling thread

    • Practice session

#include <pthread.h>#include <stdio.h>#include <stdlib.h>void* th_fn(void *arg){    int distance=(int)arg;    int i;    for(i=1;i<=distance;i++){        printf("%lx run %d\n",pthread_self(),i);        sleep(1);    }    return (void*)0;}int main(void){    int err;    pthread_t rabbit,turtle;    if((err = pthread_create(&rabbit,NULL,th_fn,(void*)50)) != 0){        printf("error!");    }        if((err = pthread_create(&turtle,NULL,th_fn,(void*)50)) != 0){        printf("error!");    }    printf("control thread id:%lx\n",pthread_self());    printf("finish!\n");    return 0;}

The results of the operation are as follows:

As can be seen from the output, the program did not create a child thread success, this is mainly because when the child thread is created, it is not possible to determine whether the main thread executes first or the child thread, from this result can be seen, the program after creating the child thread after executing the main thread, so when the main thread is finished, because it encountered a return 0, which represents the end of the entire process, so the newly created child process is also forced to exit.

It is learned that to make the child thread also be executed, the main thread should be in a wait state, and the even if main thread waits for the child thread to finish executing before exiting. Just add the Sleep (10) statement to the code before the return 0 statement, so that the main thread is blocked.


As can be seen from the running result, two threads are running alternately, the main thread executes and exits after the run is finished

    • Question 3: As can be seen from the above practice, when calling Pthread_create () to create a sub-thread, the parameter is passed by the fourth parameter, but the actual application may pass multiple parameters to the child thread, this time what to do?
    • Make all the arguments to be passed into a struct, pass the struct to the child thread to complete passing multiple arguments to the child thread

    • About the practice of question 3
#include <pthread.h>#include <stdio.h>#include <stdlib.h>typedef struct{    char name[20];    int time;    int start;    int end;}RaceArg;void* th_fn(void *arg){    RaceArg *r = (RaceArg*)arg;    int i = r->start;    for(; i <= r->end ; i++){        printf("%s(%lx) running %d\n",r->name,pthread_self(),i);        usleep(r->time);    }    return (void*)0;}int main(){    int err;    pthread_t rabbit,turtle;        RaceArg r_a = {"rabbit",10,20,50};    RaceArg t_a = {"turtle",20,10,60};    if((err = pthread_create(&rabbit,NULL,th_fn,(void*)&r_a)) != 0){        printf("error!");    }    if((err = pthread_create(&turtle,NULL,th_fn,(void*)&t_a)) != 0){        printf("error!");    }    pthread_join(rabbit,NULL);    pthread_join(turtle,NULL);    printf("control thread id:%lx\n",pthread_self());    printf("finish!\n");    return 0;}

That is, define the structure, place the parameters that need to be passed in the structure body, and then pass the pointer to the struct into the sub-thread.

    • Question 4: From the two practices above, it is known that the thread creation function creates 2 sub-threads that are stored in memory to ensure that the information they store internally does not interfere with each other and share the same process together.
    • The local variables owned by the thread are not interfering with each other, as in the case of the above practice, the memory is stored in the following way:

      But for global variables it is stored in the process data segment, and the child threads share the data in the data segment (shared resources), but this seems to have a certain impact on security
Termination of the thread
    • Active termination
    • Call the return statement in the execution function of the thread
    • Call Pthread_exit ()

    • Passive termination
    • Canceled by another thread of the same process: Pthread_cancel (Pthid), Pthid is the terminated thread identifier. This function is similar to the KILL function in a process

    • Note that when a function such as exit (0) is called in a thread, the process is terminated. In addition, when the process is not finished, the resources that are consumed by the exit thread do not release with the thread ending

    • Pthread_join () function
    • The prototype is int pthread_join(pthread_t th,void **thread_return); th as the identifier of the waiting thread, and Thread_return is the user-defined pointer used to store the return value of the waiting thread. Success returns 0
    • Invoking Pthread_join to release resources also helps to avoid excessive memory congestion

    • For the Pthread_join () function, I think the difficulty is mainly the second parameter, it is a two-level pointer variable, in order to better understand the pthread_join () function of the second parameter, you can use the following example (the code function is to add the two parameters of the incoming child thread)

#include <pthread.h>#include <stdlib.h>#include <stdio.h>typedef struct{    int d1;    int d2;}Arg;void* th_fn(void *arg){    Arg *r = (Arg*)arg;    return (void*)(r->d1 + r->d2);}int main(void){    int err;    pthread_t th;    Arg r = {20,50};    if((err = pthread_create(&th,NULL,th_fn,(void*)&r)) != 0){        printf("error!");}    int *result;    pthread_join(th,(void**)&result);    printf("result is %d\n",(int)result);    return 0;}

The results of the operation are as follows:

    • Similarly, if you want the Pthread_join () function to return more than one parameter, you will make the multiple arguments a struct and return the thread to the pointer variable that points to the struct.
Thread cleanup and control
    • Pthread_cleanup_push (void (RTN) (void ), void* Arg) function
    • Pthread_cleanup_pop (int execute) function, returns 0 if successful
    • The two appear in pairs, i.e.
while(execute){    执行线程处理函数}
    • triggers a thread to invoke cleanup function
    • call Pthread_exit
    • in response to cancel request
    • When calling Pthread_cleanup_pop with a non-0 execute parameter

      /li>
    • Practice

#include <pthread.h>#include <stdlib.h>#include <stdio.h>void clean_fun(void *arg){    char *s = (char*)arg;    printf("clean_func:%s\n",s);}void* th_fun(void *arg){    int execute = (int)arg;    pthread_cleanup_push(clean_fun,"first clean");    pthread_cleanup_push(clean_fun,"second clean");    printf("thread running %lx\n",pthread_self());    pthread_cleanup_pop(execute);    pthread_cleanup_pop(execute);    return (void*)0;}int main(){    int err;    pthread_t th1,th2;    if((err = pthread_create(&th1,NULL,th_fun,(void*)1)) != 0){        printf("error");    }    pthread_join(th1,NULL);    printf("th1(%lx) finished\n",th1);    if((err = pthread_create(&th2,NULL,th_fun,(void*)1)) != 0){        printf("error");    }    pthread_join(th2,NULL);    printf("th2(%lx) finished\n",th2);    return 0;}

From the running results can also be seen, the characteristics of the stack is after-in first out, that is, first pressed into the stack is processed first.

Comparison of process and thread initiation and termination methods

State Transitions for threads

< not finished >

20155321 "Information security system Design" Linux multi-Threading in-depth learning

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.