Multithreading and single-threaded execution efficiency issues

Source: Internet
Author: User

A mention of multithreading in general everyone's first feeling is that you can improve the program performance, in the actual operation often encountered performance problems, are trying to use multi-threaded to solve the problem, but the multi-thread program is not in any case can improve efficiency, in some cases, the contrary, will reduce the performance of the program. Here are two simple examples to illustrate the following:

Program 1:

1 Import Threading2  fromTime Import CTime3 4 classMyThread (Threading. Thread):5 def __init__ (self, func, args, name):6 Threading. Thread.__init__ (self)7Self.name =name8Self.func =func9Self.args =argsTen  One def run (self): APrint'starting', Self.name,'At :', CTime () - Apply (Self.func, Self.args) -Print Self.name,'finished at:', CTime () the  - def fun1 (x): -y =0 -      forIinchRange (x): +y+=1 -  + def fun2 (x): Ay =0 at      forIinchRange (x): -y+=1 -          - def main (): -Print'staring single thread at:', CTime () -FUN1 (10000000) inFun2 (10000000) -Print'finished single thread at:', CTime () to  +T1 = MyThread (Fun1, (10000000,), fun1.__name__) -T2 = MyThread (Fun2, (10000000,), fun2.__name__) the T1.start () * T2.start () $ T1.join ()Panax Notoginseng T2.join () -      thePrint' All done' +      A if__name__ = ='__main__': theMain ()

The result of the program execution is:

Staring single thread At:sat Dec 08 10:27:11 2012
Finished single thread At:sat Dec 08 10:27:14 2012
Starting fun1 At:sat Dec 08 10:27:14 2012
Starting fun2 At:sat Dec 08 10:27:14 2012
Fun1 finished At:sat Dec 08 10:27:21 2012
Fun2 finished At:sat Dec 08 10:27:21 2012
All done

The results show that for the same problem multithreading takes more than one time, fun1, and fun2 are computational programs, which means that both code needs to occupy CPU resources, although the use of multi-threaded but CPU resources is unique (regardless of multi-CPU multicore), only one thread at a time, resulting in multithreading can not be real concurrency, but because of the cost of switching threads, efficiency has a significant decline. As a result, in a single CPU scenario for computationally intensive programs, multithreading does not bring about efficiency gains.

Program 2:

1 Import Threading2  fromTime Import CTime3 4 classMyThread (Threading. Thread):5 def __init__ (self, func, args, name):6 Threading. Thread.__init__ (self)7Self.name =name8Self.func =func9Self.args =argsTen  One def run (self): APrint'starting', Self.name,'At :', CTime () - Apply (Self.func, Self.args) -Print Self.name,'finished at:', CTime () the  - def fun1 (x): -      forIinchRange (x): -FD = open ('1','W') + fd.close () -  + def fun2 (x): Ay =0 at      forIinchRange (x): -y+=1 -          - def main (): -Print'staring single thread at:', CTime () -FUN1 (15000) inFun2 (50000000) -Print'finished single thread at:', CTime () to  +T1 = MyThread (Fun1, (15000,), fun1.__name__) -T2 = MyThread (Fun2, (50000000,), fun2.__name__) the T1.start () * T2.start () $ T1.join ()Panax Notoginseng T2.join () -      thePrint' All done' +      A if__name__ = ='__main__': theMain ()
View Code

The result of the program execution is:

Staring single thread At:sat Dec 08 11:03:30 2012
Finished single thread At:sat Dec 08 11:03:46 2012
Starting fun1 At:sat Dec 08 11:03:46 2012
Starting fun2 At:sat Dec 08 11:03:46 2012
Fun2 finished At:sat Dec 08 11:03:55 2012
Fun1 finished At:sat Dec 08 11:03:58 2012
All done

The results show that this program uses multiple threads to improve the efficiency of single thread. This is because FUN1 is mainly the operation of the file, Fun2 is the calculation operation, single-threaded case, although the two programs mainly use different resources but the thread internal only serial execution, in the IO operation, the CPU is actually nothing to do. In the case of multithreading, if one thread waits for an IO operation, the thread is dispatched to another thread at once, and the different resources are used concurrently.

Conclusion:

Thread itself because of the cost of creating and switching, multithreading will not improve the execution speed of the program, but will slow down, but for the frequent IO operation of the program, multithreading can be effective concurrency.

For programs that contain different tasks, you can consider using one thread per task. Such a program is more clearly designed than a single-threaded program, such as production, consumer issues.

The problem of performance optimization in real development needs to take into account specific scenarios to consider whether to use multithreading techniques.

Operating system concurrency program execution characteristics: In the concurrency environment, due to the closure of the program is broken, there is a new feature: ① program and calculation no longer one by one correspondence, a program copy can have multiple computations ② concurrent programs have a mutual restriction relationship between the direct constraints embodied in a program needs another program's calculation results, Indirect restriction is embodied in several programs competing for a certain resource, such as processor, buffer, etc. ③ Concurrent program in the execution is to walk and stop, intermittent advance.editing with parallel differences ConcurrencyWhen there are multiple threads in action, if the system has only one CPU, it is impossible to actually do more than one thread at the same time, it can only divide the CPU runtime into several time periods, and then assign the time period to each thread execution, while the thread code of one time period runs, other threads are in the Hang form. In this way we call it concurrency (Concurrent). Parallel:When the system has more than one CPU, the operation of the thread may be non-concurrent. When one CPU executes a thread, another CPU can execute another thread, and two threads do not preempt CPU resources, which can be done simultaneously, which we call parallel (Parallel). difference:Concurrency and parallelism are two concepts that are similar and differentiated, parallel refers to two or more events occurring at the same time, while concurrency refers to two or more events occurring at the same interval. In a multi-channel program environment, concurrency refers to a period of time in the macro on a number of programs at the same time, but in a single processor system, each moment can only have a program to execute, so microscopic these programs can only be time-sharing alternating execution. If there are multiple processors in a computer system, these programs can be executed concurrently to be allocated to multiple processors, implementing parallel execution, that is, using each processor to process a concurrent execution of a program, so that multiple programs can be executed concurrently. [2]

Multithreading and single-threaded execution efficiency issues

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.