Python Learning Notes-Threads (2)

Source: Internet
Author: User

Before learning the basic concepts of threading and the two ways to create threads, now look at how multithreading handles the issue of race conditions (racing condition).


For example, in the following example I used the second way of creating, customizing a class, inheriting the thread class, and then customizing Run () to execute my method. In this run method, add 1 to the global variable each time


Inside the main thread, he invokes a function of his own definition, creating 5,000 threads in the function, each of which joins a list and then uses join for each object, which ensures that the main thread waits until all the child threads are finished. Final output results


Import timeimport threadingsome_var = 0class incrementthread (Threading. Thread):     def run (self):         #we   want to read a global variable         #and  then increment it        global some_var         read_value = some_var         print  ("some_var in %s is %d"  %  (Self.name, read_value))         some_var = read_value + 1         print  ("Some_var in %s after increment is  %d " %  (Self.name, some_var)) Def use_increment_thread ():     Threads = []    stArt=time.time ()     for i in range (:     )    t = incrementthread ()          Threads.append (t)         t.start ()     for t  in threads:        t.join ()     print (" total time %s "% (Time.time ()-start))     print  (" after 5000  modifications, some_var should have become 5000 ")     print  ( "after 5000 modifications, some_var is %d"  %  (Some_var,)) Use_increment_ Thread ()------------------Total time 1.7780036926269531after 5000 modifications, some _var should have become 5000after 5000 modifications, some_var is  4987


Can see the result is not 5000, this is why? If you look at the process, you will find that some threads have just acquired a value that has not yet been processed, and the power of execution is passed on to another thread, which results in a count error. To ensure that every thread succeeds in executing the code he should execute, we can add a lock.

Some_var in Thread-1524 are 1523some_var in Thread-1524 after increment are 1524some_var in Thread-1525 are 1524some_var in T hread-1526 are 1524some_var in Thread-1526 after increment are 1525some_var in Thread-1527 are 1525


Here is the revised code, by using the lock () function, we acquire () before executing the code, and then release (), the other threads cannot perform the same operation until the current thread completes the code.

Some_var = 0lock=threading. Lock () Class incrementthread (threading. Thread):     def run (self):         #we   want to read a global variable         #and  then increment it        global some_var         lock.acquire ()         read_ value = some_var        print  ("some_var in % s is %d " %  (self.name, read_value)          some_var = read_value + 1        print  ("some _var in %s after increment is %d " %  (Self.name, some_var)          lock.releaSE () def use_increment_thread ():    threads = []     Start=time.time ()     for i in range (:     )    t = incrementthread ()          Threads.append (t)         t.start ()     for t  in threads:        t.join ()     print (" total time %s "% (Time.time ()-start))     print  (" after 5000  modifications, some_var should have become 5000 ")     print  ( "after 5000 modifications, some_var is %d"  %  (Some_var,)) Use_increment_ Thread ()---------------total time 1.6369926929473877after 5000 modifications, some_ var should have become 5000after 5000 modifications, some_var is 5000 


This article is from the "Mapo Tofu" blog, please be sure to keep this source http://beanxyz.blog.51cto.com/5570417/1866269

Python Learning Notes-Threads (2)

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.