Single-threaded and multi-threaded advantages and disadvantages _ multithreading

Source: Internet
Author: User
Tags mongodb postgresql
The pros and cons of single-threaded and multi-threaded

The advantages of multi-threaded processing

Synchronization applications are easier to develop, but are typically less efficient than multithreaded applications because they need to be completed before a new task can be started. If the synchronization task is completed longer than expected, the application may not respond. Multithreading can run multiple processes at the same time. For example, a word processor application can check spelling (as a separate task) while you are working on the document. Because multithreaded applications divide programs into separate tasks, you can significantly improve performance in the following areas:
Multithreading enables programs to respond more quickly because the user interface can be active while doing other work.
Tasks that are not currently being processed can cede processor time to other tasks.
Tasks that take up a lot of processing time can periodically cede processor time to other tasks.
You can stop a task at any time.
You can prioritize each task individually to optimize performance.

Whether you need to create a multithreaded application depends on several factors. Multithreading is best used in the following situations:
Time-consuming or heavy processor-intensive tasks block user interface operations.
Each task must wait for external resources (such as remote files or INTERNET connections).

For example, an INTERNET application "ROBOT" is used to track links on a WEB page and to download files that meet certain criteria. This application can download individual files synchronously, or you can use multithreading to download multiple files at the same time. Multithreaded methods are much more efficient than synchronization methods because the remote WEB server's response is very slow in some threads, and the file can be downloaded.

Here are examples of multithreading
Also in the DOS era, people are looking for a multitasking implementation. Then there is a TSR type of background-resident program, more representative of side KICK, Vsafe and other excellent TSR procedures, such programs and applications do give users a great convenience in the use of computers, such as side KICK, the program can be programmed in the state without the editor, While editing the source program, while compiling and running, very convenient. However, the fatal flaw in the DOS single task operating system is doomed to not be able to develop a real multitasking program under DOS. Entering the WINDOWS3.1 era, this situation is still not fundamentally changed, one application can only do something. For example, database queries, unless the application is well compiled, the entire system will not respond to user input during the query.
In the Windows NT and Windows 9X era, the situation has been radically changed, and the operating system has implemented multitasking in real sense (strictly speaking, Win9x). An application, when needed, can have many threads of execution, each thread is a small execution program, the operating system automatically allows each thread to share CPU resources, to ensure that no one thread can cause the system to deadlock. In this way, when programming, you can move the time-consuming task to the background, in the foreground with another thread to accept the user's input. For those programming tasks that require high real-time requirements, such as network customer service, serial communication and other applications, the implementation of multithreading will undoubtedly greatly enhance the usability and stability of the program.


=====================================================================================



Disadvantages: Increase the cost of scheduling and management, bring some uncertainty, need complex synchronization mechanism, avoid deadlock and so on.
Benefits: To a certain extent, improve the response speed, in the case of multi-core or more fully utilize the CPU resources.



=====================================================================================


Single-threaded is the program execution, the running of the program path (the processing of things) is sequential order down, must be processed in the front, the following will be executed to.
Multithreading, for example, that is, the program can be executed at the same time more than 2 similar operations, such as a number of search agents or mass email multithreaded software, because the operation of the need for the return of the network information spent a long time, but for the CPU is idle, if it is a sequential execution,   Then it will take you a long time to search thousands of IP. If you use multithreading, you can add other searches while waiting, and then wait, which can improve efficiency. However, multithreading and multiple processes common to some resources to consider the problem seems to be the same, for some public resources or public variables to visit and modify to pay attention to the special, need some lock something, there are sequential issues to consider.
The purpose of multithreaded programming is to "Maximize CPU resources", when the processing of a thread does not need to occupy CPU and only with resources such as I/o,oembios, so that other threads that need to occupy CPU resources have access to CPU resources. Each program executes with a process, and each process has at least one main thread. This thread is actually a clue to the execution of the process, in addition to the main thread you can add additional threads to the process, or add other execution clues, which can be seen in some ways as an added multitasking function to an application. When the program is running, you can suspend or run these threads based on various conditions, especially in a multiple-CPU environment where these threads are running concurrently. Multithreading is the multiple threads in a process. This allows an application to have multitasking capabilities. Multi-process technology can also achieve this, however, the high consumption of creating processes (each with separate data and code space), the inconvenient communication between processes (message mechanism), the process switching time is too long, which led to multithreading, for single CPU (not open Hyper-threading), Only one thread can be executed at the same time, so if you want to implement multitasking, you can only get a time slice per process or thread, within a time slice, only one thread can execute, and then follow some policy for other threads to execute. Because time slices are very short, this gives the user the feeling that there are many threads executing at the same time. However, there is a cost to thread switching, so if you are using multiple processes, you need to switch the memory required by the process that the thread is attached to, which can cost a lot of time. The cost of thread switching is minimal, and threads can share memory. Therefore, the use of multithreading in switching costs much less than many processes. However, thread switching takes time, so it takes more time to execute a process with two threads than two times for a thread's process to execute. That is, multithreading will not improve the execution speed of the program, but will reduce the speed, but for users, can reduce the user's response time. The above results are only for single CPU, if the use of Hyper-Threading technology for multiple CPUs or CPUs, the use of multithreading technology will improve the execution speed of the program. Because single-threaded is mapped to only one CPU, and multithreading is mapped to multiple CPUs, Hyper-Threading technology is inherently multithreaded, so it speeds up the execution of programs.


====================================================================================



If a thread has a deadlock, the only thing that can prove is that the application has a problem, which is not a thread's fault.

The advantages of line threads relative for process:
1. Small cost
2. Good sharing of resources.

The disadvantage of line threads relative for process:
1, shared resources need to spend a certain amount of lock resources, synchronization is relatively complex.
2. A thread crash can cause the entire process to crash, which of course is problematic for its own application



====================================================================================



The CPU allocates cup processing time in the form of a time slice, and when a process completes several things in a synchronized way, the process must complete the first thing and then do the second thing, so that the CPU is requested to do what is required in order. In this single-threaded mode of work, if you think of the Cup as a total of 100 time slices, the CPU may have spent only 10 of the time to deal with the current process of things to do, only the CPU 10% of the time slice, and other time is wasted, of course, In fact, the CPU's working mode or to do one thing later to do another thing, but the cup processing speed is very fast, quickly deal with the completion of the requested cases.



In order to improve the CPU utilization rate, the use of multithreading to complete a few things at the same time without interference, if the current process to complete three things 1, 2, 3, then the CPU will be 10% of the time to handle the 3 things, so that the CPU utilization rate reached 30%, greatly improve the utilization of the CPU. The advantages of multithreading are especially noticeable in dealing with some special occasions. For example, download the file, you want to download while showing progress while saving, in this case, if not with multithreading, there is no accident will normally block the main thread, such as the progress of the progress bar has not changed with the volume of the download, so that the entire form can not move, with multiple threads to solve this problem very well.



Here's a life example that might better understand multithreading: Go back to see your girlfriend Cook, normally, she would put the washing (meat) in the pot before cooking, and then wash other dishes or deal with other things, such as: washing dishes, cleaning table to prepare for dinner, people or a person, but she does a few things at the same time, This will greatly improve efficiency. The total word is: The CPU still has to spend the same amount of time to complete all things, but multithreading can allow the CPU to insert a lot of things at the same time, visually let users feel that the computer at the same time to help him deal with a number of things to better improve the user experience.



Once you understand the benefits of multithreading, you need to know what kind of situations you should use multithreading. Because it's not that all cases are good with multithreading, because of multithreading, the CPU also takes time to maintain, the CPU processing the request of the thread between the threads will also take time to switch, so under normal circumstances can not use more than a thread, and sometimes it will not outweigh the gains. In most cases, to use multithreading is the main need to deal with a large number of IO operations or the processing of the situation needs to spend a lot of time and so on, such as: Read and write files, video image collection, processing, display, save and so on.


Alibaba Cloud Hot Products

Elastic Compute Service (ECS) Dedicated Host (DDH) ApsaraDB RDS for MySQL (RDS) ApsaraDB for PolarDB(PolarDB) AnalyticDB for PostgreSQL (ADB for PG)
AnalyticDB for MySQL(ADB for MySQL) Data Transmission Service (DTS) Server Load Balancer (SLB) Global Accelerator (GA) Cloud Enterprise Network (CEN)
Object Storage Service (OSS) Content Delivery Network (CDN) Short Message Service (SMS) Container Service for Kubernetes (ACK) Data Lake Analytics (DLA)

ApsaraDB for Redis (Redis)

ApsaraDB for MongoDB (MongoDB) NAT Gateway VPN Gateway Cloud Firewall
Anti-DDoS Web Application Firewall (WAF) Log Service DataWorks MaxCompute
Elastic MapReduce (EMR) Elasticsearch

Alibaba Cloud Free Trail

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.