Line Program Control system
1. Thread-to-process relationships
Thread: The smallest unit in a computer that runs independently.
At the user's perspective: Multiple threads are executed concurrently.
Operating system angle: each thread executes alternately
The above only for single-core CPUs
On multi-core CPU hosts, multiple threads can run concurrently.
Why is multithreading supported in case of a process? Multithreading is relatively multi-process with the following advantages:
1. In the case of multiple processes, each process has its own separate space address. Multiple threads within the same process share in-process space addresses
2. In the system scheduling aspect: The process space is independent, the thread shares the space, the switch between threads is much faster than the process between the switch.
3. In the context of communication mechanisms: inter-process data are independent of each other, and communications must be made in a dedicated communication mode, through the operating system, within the same process
Thread sharing data space, directly modified, do not have to enter the operating system, convenient time-saving.
Summarize the above advantages: Save: Save resources, save time
4. Improve application response speed
5. Improve the efficiency of multiple processors
6. Improve the program structure
Although threads share space addresses within the process, they also have their own private data
1. Threading Number Thread ID
2. Registers
3. Stacks
4. Information mask
5. Priority level
6. Thread-Private storage space
Linux supports POSIX multithreaded interfaces, called Pthread.
Writing a multithreaded program under Linux requires the use of a header file Pthread.h, which you need to use when linking LIBPTHREAD.A
2. Create a thread
1. Thread creation function pthread_create
The number of times a function is executed is limited to one pthread_once
2. Thread properties A parameter of the Pthread_create function pthread_attr_t, a struct
3. Thread termination (1) return (2) pthread_exit ()
Return or call exit in the main thread, the entire process terminates, so the main thread cannot return prematurely
If the main thread calls Pthread_exit, then only the main thread dies, the process does not end, the other threads within the process do not terminate, and the process terminates until all thread ends.
The most important problem with thread termination is the resource release problem: Pthread_cleanup_push (), Pthread_cleanup_pop () is used to automatically release resources. Two functions must appear in pairs {}
Another issue: Thread synchronization issues.
3. Private Data
4. Thread synchronization
1. Mutual exclusion Lock
2. Condition variables
3. Asynchronous signals
5. Error handling
1. Error checking
2. Error code
3. Error message
Strerror string.h
Perror stdio.h
Linux C Program Threads (18)