Multi-threaded programming under Linux (System programming) __HTML5

Source: Internet
Author: User
Tags data structures posix terminates kali linux

One, the basic concept of threading
1, the definition of the thread:
Threads are also referred to as lightweight process (LWP) Computer science terminology, which refers to the scheduling unit of a running program.

A thread is an entity in a process, a process can have multiple threads, and a thread must have a parent process. A thread does not own system resources, only some data structures that must be run, and it shares all the resources owned by the process with other threads of the parent process. Threads can create and undo threads, enabling concurrent execution of programs. Generally, threads have three basic states of ready, blocking, and running.

In a multi-CPU system, different threads can run simultaneously on different CPUs, even when they belong to the same process. Most multiprocessor-enabled operating systems provide a programming interface to allow processes to control the degree of association between their threads and the processors.

2, threading vs. process
1> definition
A process is a program with a certain independent function about a running activity on a data set, and a process is an independent unit of resource allocation and scheduling for a system.

Threads are finer than the granularity of a process, threads are branches in the process execution flow, and a part of the process has resources.

2> relationship
One thread can create and revoke another thread, which can be executed concurrently between multiple threads in the same process.

In relative processes, a thread is a concept that is closer to the execution body, it can share data with other threads in the process, but has its own stack space and has a separate execution sequence.

3> difference:
A. Address space and other resources: processes are independent of each other, shared among threads of the same process. Threads within a process are not visible in other processes.
B. Communications: interprocess communication IPC, where threads can directly read and write process data segments (such as global variables) to communicate--requiring process synchronization and mutual exclusion means to ensure data consistency.
C. Scheduling and switching: Thread context switching is much faster than process context switching.
D. In a multithreaded OS, a process is not an executable entity.

4> Advantages and Disadvantages
Threads and processes have advantages and disadvantages in their use: Thread execution costs are small but not conducive to resource management and protection; The process is the opposite. At the same time, threads are suitable for running on SMP machines, while processes can migrate across machines.

3, multithreading

The main function and the signal processing function are multiple control processes in the same process address space, multithreading is also the case, but more flexible than signal processing functions, signal processing function control flow is only in the signal delivery, after processing the signal to end, and multithreading control process can coexist for a long time, The operating system schedules and toggles between threads, just like scheduling and switching between multiple processes.

The following process resources and environments are shared between multiple threads in the same process:
1. File Description Chart
2. How each signal is processed (sig_ign, SIG_DFL, or custom signal processing function)
3. Current working directory
4. User ID and Group ID

Private resources between multiple threads of the same process:
1. Thread ID (is a positive integer that is valid only within the current process and is used to identify the thread)
2. Context, including the values of various registers, program counters and stack pointers
3. Stack space
4. errno variable
5. Signal Shielding Word
6. Scheduling priority

The line threading function I'm going to introduce is defined by the POSIX standard, called POSIX thread or pthread. The Linux thread function is located in the Libpthread shared library, so add the-lpthread option at compile time . two, thread control

1, Thread creation

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

Return value: Successfully returned 0, error return error number
First parameter thread: Thread ID (output type parameter)
The second parameter attr: Thread properties, typically set to null (indicating that the thread attribute takes the default value)
Third parameter start_routine: function pointer to code that the new thread is about to execute
Fourth argument arg: What type of interpretation does this pointer define by the caller himself-->null

After calling Pthread_create () in one thread to create a new thread, the current thread returns from Pthread_create () and continues to execute, while the code executed by the new thread passes us to the Pthread_create function pointer Start_ Routine decided.

code example:

The above example shows that on Linux, the pthread_t type is an address value, and multiple threads that are part of the same process call Getpid () to get the same process number, and the thread number of the call Pthread_self () is different.
If any one of the threads calls exit or _exit, all threads of the entire process terminate, because return from the main function is equivalent to calling exit (explained below).

Run Result:

2, terminating the thread
1> If you need to terminate only one thread without terminating the entire process, there are three ways:
1. Return from the thread function. This method does not apply to the main thread, and return from the main function is equivalent to calling exit.
2. A thread can invoke Pthread_cancel to terminate another thread in the same process.
3. Threads can call pthread_exit terminate themselves.

2> terminates a thread or executes a stream:

#include <pthread.h>
void pthread_exit (void *retval);

RetVal is a void * type, as is the use of the return value of a thread function, other threads can invoke Pthread_join (described later) to obtain this pointer.

Note that the memory unit that the Pthread_exit or return pointer points to must be global or allocated with malloc, and cannot be allocated on the stack of thread functions, because the thread function has exited when other threads get the return pointer.

3> Cancel Thread

#include <pthread.h>
int pthread_cancel (pthread_t thread);

The thread is allowed to be canceled, the exit result is-1, the thread itself cancels (not recommended) The exit result is 0.

3, Thread waiting
1> Why to wait for a thread.
The threads that the main function executes are called the main thread, and the execution order of multithreading is determined by thread scheduling
The main thread must recycle other threads, or it will create a zombie-like situation (memory leak).
Conclusion: threads must be waiting

2> gets the thread of the current thread tid:pthread_self

#include <pthread.h>
 pthread_t pthread_self (void);

(only valid within the current process, as the thread's unique identifier)

3> Thread wait function:

#include <pthread.h>
int pthread_join (pthread_t thread, void **retval);

Return value: Successful return of 0, failure return error code.
Parameter thread: The thread number, that is, the TID to wait for the thread
Parameter retval: To wait for the thread's exit code (output type parameter)

The thread that calls the function suspends the wait until the thread with ID thread terminates. Thread threads terminate in different ways, and the termination status obtained by Pthread_join is different, summarized as follows:
1. If the thread thread returns via return, the value_ptr points to a cell that holds the return value of the thread function.
2. If the thread thread is called Pthread_cancel by another thread, the value_ptr point to the cell that holds the constant pthread_canceled.
3. If the thread thread is pthread_exit terminated by itself, the cell to which the value_ptr points is stored as a parameter passed to Pthread_exit. If you are not interested in the end state of the thread threads, you can pass NULL to the VALUE_PTR parameter.

4> when a multithreaded execution occurs, the entire process is suspended as long as one thread fails (the operating system signals it to recycle the resource and the other threads exit). When the thread is running, the thread can only run properly, and the exit code indicates its state of operation.
thread waiting is only one way: blocking wait

4, comprehensive examples

1 #include <stdio.h> 2 #include <pthread.h> 3 #include <unistd.h> 4 5 void* thread1 (void* val1)
  6 {7 printf ("Thread1 is returning\n");
  8 printf ("%s:pid is%d,tid is%u\n", (char*) val1,getpid (), pthread_self ());
 9 return (void*) 0;//thread termination mode 1, back to all void* thread2 (void* val2) ("Thread2 exiting\n"), by returning;
 printf ("%s:pid is%d,tid is%u\n", (char*) val2,getpid (), pthread_self ()); Pthread_exit ((void*) 2);/thread termination mode 2, Pthread_exit exit} void* thread3 (void* val3) ("%s:pid I
 S%d,tid is%u\n ", (char*) val3,getpid (), pthread_self ());   
 while (1) {printf (' thread3 is running,waiting for to be canceled\n ');/thread termination mode 3, by other thread C Ancel
 Sleep (1);
 the int main () pthread_t tid1;
 pthread_t Tid2;
 pthread_t tid3;
 void* ret; //thread1 return Pthread_create (&tid1,null,thread1, "thread1");Thread 1 creates pthread_join (Tid1,&ret),//wait thread1 to printf ("Thread1 return,return code is%d\n", (int) ret); //thread2 exit Pthread_create (&tid2,null,thread2, "thread2")/thread 2 Create Pthread_join (TID2,
 &ret);//wait thread2-printf ("Thread2 exit,exit code is%d\n", (int) ret);
 //thread3 Cancel Pthread_create (&tid3,null,thread3, "thread3");/thread 3 Create a sleep (3);      Pthread_cancel (TID3)/thread termination mode 3, Thread_cancel cancelled by other threads Pthread_join (Tid3,&ret);//wait thread3 48
 printf ("Thread3 cancel,cancel code is%d\n", (int) ret);
 printf ("Main thread run:pid is%d,tid is%u\n", Getpid (), pthread_self ());
 I return 0; 53}

Run Result:

Careful friends will find out why 3 threads of PID and Tid are the same. The reason is that PID is actually the main thread of the process number, the same as 1514, so since it is a different thread, and because the thread number is to determine the identity of a thread, why 3 thread number is still the same.
In fact, the review code is a way to verify that 3 threads terminate, and we wait for each thread to terminate, after invoking the thread wait function, the main thread reclaims its resources, including, of course, the thread ID, and after thread 1 is recycled, we create thread 2, The system will give priority to the Line 1 route ID just reclaimed to be assigned to thread 2, and when thread 2 is terminated, the thread number is recycled again and then allocated to thread 3, which is why we see that different 3 threads have the same tid.

If you have questions about the above question, see the following code:

  1 #include <stdio.h> 2 #include <pthread.h> 3 #include <unistd.h> 4 5 void* thread1 (void* val1)
  6 {7 printf ("Thread1 is returning\n");
  8 printf ("%s:pid is%d,tid is%u\n", (char*) val1,getpid (), pthread_self ());
 9 return (void*) 0;//thread termination mode 1, back to all void* thread2 (void* val2) ("Thread2 exiting\n"), by returning;
 printf ("%s:pid is%d,tid is%u\n", (char*) val2,getpid (), pthread_self ()); Pthread_exit ((void*) 2);/thread termination mode 2, Pthread_exit exit} void* thread3 (void* val3) ("%s:pid I
 S%d,tid is%u\n ", (char*) val3,getpid (), pthread_self ());          while (1) {printf ("Thread3 are running,waiting for to be canceled\n")/thread termination mode 3, by other thread C Ancel 23
 Sleep (1);
 the int main () pthread_t tid1;
 pthread_t Tid2;
 pthread_t tid3;
 void* ret; //thread1 return Pthread_create (&tid1,null,thread1, "thread1");/thread 1Create A//Pthread_join (Tid1,&ret);//wait thread1 ("Thread1 return,return code is%d\n", (int) ret); //thread2 exit Pthread_create (&tid2,null,thread2, "thread2")/thread 2 Create//Pthread_join (TID
 2,&ret);//wait thread2-printf ("Thread2 exit,exit code is%d\n", (int) ret);
 //thread3 Cancel Pthread_create (&tid3,null,thread3, "thread3");/thread 3 Create a sleep (3);      Pthread_cancel (TID3)/thread termination mode 3, Thread_cancel cancelled by other threads//Pthread_join (Tid3,&ret);//wait thread3 48
 printf ("Thread3 cancel,cancel code is%d\n", (int) ret);
 printf ("Main thread run:pid is%d,tid is%u\n", Getpid (), pthread_self ());
 Wuyi Pthread_join (tid1,null);
 Pthread_join (Tid2,null);
 Pthread_join (Tid3,null);
 0; 56}

Adjust the code: the middle of the program to the thread of the waiting annotation, at the end of the program run to the 3 thread waiting, during which 3 child threads in a zombie state.
Run Result:

5, Thread properties
Two attributes of a thread: binding and separable.
At any point in time, threads are either associative (joinable) or detached (detached). A thread that can be combined can be retrieved by other threads and killed by its resources. Its memory resources, such as stacks, are not released until they are reclaimed by another thread. In contrast, a detached thread cannot be recycled or killed by another thread, and it's saved
The storage resource is automatically released by the system when it terminates.

By default, threads are created to be combined.
In order to avoid memory leaks, each of the associative threads should either be shown to be recycled, call pthread_join, or be detached by calling the Pthread_detach function.

Because after calling Pthread_join, if the thread is not running, the caller will be blocked, and in some cases we do not want to. Improvement methods:
1> can add code to a child thread:

Pthread_detach (Pthread_self ())

2> Parent Thread Call:

Pthread_detach (thread_id) (not blocked, can be returned immediately)

This sets the state of the child thread to separate (detached), detached), and, as a result, all resources are automatically freed when the thread is run.

The thread can be detached or detached actively.
When a process is set to detach a thread, the main thread does not need to wait on it, and the system is automatically recycled when it is finished running.

Thread Detach Code:

  1/************************************** 2 * Document Description: THREAD_DETACH.C 3 * Author: Chaixiaoshe 4 * Create time: May 22, 2017 Monday 20:53 18 sec 5 * Development environment: Kali linux/g++ v6.3.0 6 ****************************************/7 #include <stdio.h> 8 #include <unis Td.h> 9 #include <pthread.h> #include <string.h> void* thread4 (void* val4) {print F ("%s:thread4 child detach,thread4 Tid is%d\n", (char*) val4,pthread_self ());/thread 4 active separation Pthread_detach (pthread_
 Self ()); Return (void*) 0;//thread terminating void* thread5 (void* val5) {printf ("%s:thread5 father Detach,thread5 T ID is%d\n ", (char*) val5,pthread_self ())//Line > 5 separated by return (void*) 0;//thread Terminator int main () 25 {2
 6 pthread_t Tid4; int ret = pthread_create (&AMP;TID4,NULL,THREAD4, "THREAD4 is Running");/thread Create/if (ret!= 0) pr
 intf ("creat thread4 Error:errno is%d,error info is%s\n", Ret,strerror (ret)); //wait---thread waiting for SLEEP (1);
 int tmp = 0;
 TMP = Pthread_join (tid4,null);
 (0 = tmp) printf ("Thread4 wait success\n");
 Or else Notoginseng printf ("Thread4 wait failure\n");
 pthread_t TID5;                 ret = Pthread_create (&AMP;TID5,NULL,THREAD5, "THREAD5 is Running");/thread Create A/(ret!= 0) 42
 printf ("creat thread5 Error:errno is%d,error info is%s\n", Ret,strerror (re t));
 Sleep (1); TMP = Pthread_detach (TID5);//thread detach (0 = tmp) (+) ("Thread5 is detached su")
  Ccess\n ");
 M/F ("THREAD5 is detached failure\n"); TMP = Pthread_join (tid5,null);//thread waits for (0 = tmp) printf ("Thread5 wait success\n
 ");
 Or else printf ("Thread5 wait failure\n");
 0;  59}

Run Result:

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.