Python3.4 multithreading first attempt

Source: Internet
Author: User

Python3.4 multithreading first attempt

Inherit from threading. thread, and create 7 threads, set a local variable attribute, and generate 8 random numbers randomly in the Thread's run function, and store the random numbers of their respective threads using the local attribute.

Call the start function to start the thread. If the join function is called, it becomes serial. After the first thread is executed, the second thread is executed in sequence, and the main thread is executed.

(Note: python version 3.4)

 

Import threadingimport timeimport random # inherits threading. Thread and reloads the run function. Class jdThread (threading. thread): def _ init _ (self, num): threading. thread. _ init _ (self) self. num = num self. create_time = time. time () self. local = threading. local () # local has global access. The main thread and sub-thread can access it, but its value is related to the current thread. # If you want to save a global value in the current thread, and the respective threads do not interfere with each other. The local class is used. Actually, it is a dictionary def run (self): self. local = [] time. sleep (1) print ("Thread", self. num, "created") for I in range (8): self. local. append (random. randrange (10) # displays the thread status and the randomly generated 10 numbers print (threading. currentThread (), self. local) print (time. time ()-self. create_time) print ("Thread", self. num, "end") print ("\ n") print ("main thread start") for item in range (7): t = jdThread (item) t. start () # The join function controls the thread execution sequence. Do not call the join function before start # t. join () # view the running status of the thread background using the isDaemon function # print (t. isDaemon () print ("main thread ends ")


 

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.