Linux-Multithreaded programming

Source: Internet
Author: User

Basic definition of process and thread

Processes (Process)
The term of the program and the resources it contains
Program: Executable program code
Resources: Open file, suspend signal, address space, data segment, etc.
Threads (thread)
Objects that are active in a process
Independent program counters, process stacks, and a set of process registers
Save memory, reduce management overhead, and quickly switch

Process
Resource allocation units
The context component of the process
Process Control block PCB: Includes process number, status, priority, and general information about the distribution of data in body segments and data segments
Body segment (text segment): Executable code that holds the process
Data segment: The stored process statically generated data structure
User stacks (Stack)
Thread
CPU Dispatch basic unit

Process Execution status related information
进程 ID、进程组 ID、用户 ID和组 ID 工作环境(Environment) 工作目录(Working directory)程序指令(Program instructions) 寄存器(Registers) 栈(Stack) 堆(Heap) 文件描述符(File descriptors) 信号(Signal actions ) 共享库(Shared libraries) 进程间通信手段(Inter-process
Basic features of threading

is an entity of a process that can be used as the unit of Independent Dispatch and dispatch of a system
There are different states, there are various primitives that control threads, including creating and revoking threads, etc.
does not own system resources (all resources are owned by dependent processes, resources are assigned to processes)
Multiple threads in a process can execute concurrently
Threads created in a process can perform different parts of the same program
You can also execute the same code
Low system overhead, fast switching
Multiple threads of a process are active in the address space of the process, sharing global variables

Multiple threads in the same process share the process's virtual space
Process Code Snippet
Public data for a process
With these shared data, threads can easily communicate with each other.
File descriptor for Process open
The processor of the signal
The current directory and process user ID of the process and the process group ID
Description
For different processes, with independent data space, data transmission can only be done by means of communication, which is time-consuming and inconvenient.

Threads are necessary to implement concurrency
Thread ID
Each thread has its own unique thread ID
Value of the Register group
When creating a thread, the state of the Register collection of the original thread must be saved
The stack of threads
The thread must have its own stack of functions so that function calls can execute normally, not affected by other threads
Error return code
Different threads should have their own error return code variable
The signal screen code of the thread
The thread's signal mask should be managed by the thread itself, but all threads share the same signal processor
Priority of the thread

User thread

User threads exist in user space and are implemented by line libraries
Line libraries provides support for thread creation, scheduling, and management without the need for kernel support
The kernel does not know the user-level thread, and all threads are created and dispatched within the user space without the need for kernel intervention
Scheduling of user-level threads in process units
Advantages
Thread switching within the same process does not need to be converted to the kernel, the scheduling algorithm is process-specific
Disadvantages
System scheduling congestion problem, can not make full use of multi-processor

directly supported by the operating system, the kernel performs thread creation, scheduling, and management within its space
Because thread management is done by the operating system, the creation and management of kernel threads is slower than the creation and management of user threads
Advantages
Multi-processor support, fast multi-threaded in user process, kernel thread switching speed
Disadvantages
High system overhead for user thread switching

Threading-Multithreaded Model

Many-to-one model
Mapping many user-level threads to a kernel thread
Thread management in user space, high efficiency
The unit of the processor dispatch is still the process
Disadvantages
If a thread executes a blocking system call, the entire process blocks
Because only one thread accesses the kernel at any time, multiple threads cannot run concurrently on multiple processors
Description
User-level line libraries implemented on operating systems that do not support kernel-level threading also uses a many-to-one model

One-to-one model
Map each user thread to a kernel thread
Allow another thread to continue executing when one thread is blocking
Allow multiple threads to run on multiprocessor system
Provides better concurrency than many-to-one models
Disadvantages
Creating a user thread requires creating a corresponding kernel thread
The overhead of creating a kernel thread affects the performance of the application, and most implementations of this model limit the number of threads supported by the system

Many-to-many models
Multiplexing many user-level threads onto the same number or a smaller number of kernel threads
The number of kernel threads may be related to a particular application or specific machine
Overcoming the disadvantages of the first two models
Developers can create as many threads as necessary, and the corresponding kernel threads can run concurrently on multiprocessor systems
When a thread executes a blocking system call, internal nuclear power dispatches another thread to execute

Pthread background

Early hardware vendors mainly use private version line libraries, the implementation of the difference is very large, developers are difficult to develop portable threading applications
A standard programming interface is required to maximize the performance of the thread
For Unix systems, the IEEE POSIX 1003.1c Standard (1995) defines such interfaces
Threads implemented in compliance with this standard are called POSIX threads, or pthreads
Pthreads defines a set of C language programming interfaces and function calls
Includes a pthread.h header file and a line libraries

基于POSIX标准的线程编程接口包括一个pthread.h头文件和一个线程库编译方法gcc  –g  **.c   -o ***  –lpthread 功能线程管理支持线程创建/删除、分离/联合,设置/查询线程属性互斥处理同步,称为“mutex”创建/销毁、加锁/解锁互斥量,设置/修改互斥量属性条件变量支持基于共享互斥量的线程间通信建立/销毁、等待/触发特定条件变量,设置/查询条件变量属性
线程管理支持线程创建、分离、联合等,还包括线程属性的设置/查询 互斥处理同步,称为“mutex”提供创建、销毁、加锁和解锁互斥量也包括补充的修改互斥量属性功能,并用它去设置或者修改与互斥相关的属性 条件变量支持基于共享互斥量的线程间通信,以开发者的特定条件变量为基础。包括基于特定条件变量的建立、销毁、等待和信号触发设置/查询条件变量属性的功能也包括在内
Thread Management thread creation
const pthread_attr_t *attr,void *(*start_routine) (void*),void * arg); 参数说明thread:要创建的线程id指针attr:创建线程时的线程属性v(*start_routine)(void*):返回值是void*类型的指针函数arg:start_routine的参数返回值成功返回0
#include <pthread.h>#include <stdio.h>void*create (void*arg) {printf("New thread created ..... ");}intMainintargcChar*argv[]) {pthread_t TIDP;intError Error=pthread_create (&AMP;TIDP, NULL, create, NULL);if(Error! =0)      {printf("Pthread_create is not created ... ");return-1; }printf("Prthread_create is created ... ");return 0;}
const pthread_attr_t *attr,void *(*start_routine) (void*),void * arg); 仅允许传递一个参数给线程待执行的函数如何传递多个参数解决途径构造一个包含所有参数的结构,将结构指针作为参数传递给pthread_create()所有参数必须利用(void *)来传递
获取线程自身的id函数原型pthread_t pthread_self(void);返回值调用线程的线程id比较线程ID函数原型int pthread_equal(pthread_t tid1, pthread_t  tid2);参数tid1:线程1的idtid2:线程2的id返回值相等返回非0值否则返回0
Thread termination
正常终止方法1:线程自己调用pthread_exit()void pthread_exit(void *rval_ptr);rval_ptr:线程退出返回的指针,进程中其他线程可调用pthread_join()访问到该指针方法2:在线程函数执行return 非正常终止其它线程的干预自身运行出错

Synchronous mode (non-detached state)
Wait for the new creation thread to end
Only if the Pthread_join () function returns, the created thread is terminated to free the system resources that it occupies
Asynchronous mode (detach state)
Not waiting by another thread, terminating the thread and freeing the system resources at the end of its own run

函数原型intvoid ** rval_ptr);功能调用者将挂起并等待新进程终止当新线程调用pthread_exit()退出或者return时,进程中的其他线程可通过pthread_join()获得进程的退出状态使用约束一个新线程仅仅允许一个线程使用该函数等待它终止被等待线程应处于可join状态,即非DETACHED状态返回值成功结束返回值为0,否则为错误编码 说明类似于waitpid()
pthread_detach(pthread_t thread) 功能执行该函数后线程处于DETACHED状态处于该状态的线程结束后自动释放内存资源,不能被pthread_join()同步说明当线程被分离时,不能用pthread_join()等待其终止状态为避免内存泄漏,线程终止要么处于分离状态,要么处于同步状态

Function description
Client
Use threads to send characters from standard input to the server
Displays the characters returned from the server side to the standard output in the main thread
Server-side
The data sent from the client is returned to the client as is, and each client corresponds to a thread on the server

Linux-Multithreaded programming

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.