Python: thread, python thread

Source: Internet
Author: User

Python: thread, python thread
Thread

1. threads and processes

Process: The program in progress. A process can process a task. For a person, a person is a process. A process contains threads.

Thread: Lightweight Process. Only one thing can be done at a time point. One person can do multiple things, each of which is a thread.

2. The thread is the minimum unit of CPU scheduling. Process is the minimum unit for resource allocation.

3. The time-space overhead of enabling a thread is lower than that of enabling a process, and the cpu switching between threads is faster than switching between processes.

4. A program can contain multiple processes and threads at the same time.

1) Call the module to enable the thread

Import osimport timefrom threading import Threaddef func (): # subthread time. sleep (1) print ('Hello world', OS. getpid () thread_lst = [] for I in range (10): t = Thread (target = func) t. start () thread_lst.append (t) [t. join () for t in thread_lst] print (OS. getpid () # main thread

2) Enable the thread of the call class

Import osimport timefrom threading import Threadclass MyThread (Thread): count = 0 # static attribute def _ init _ (self, arg1, arg2): super (). _ init _ () self. arg1 = arg1 self. arg2 = arg2 def run (self): MyThread. count + = 1 time. sleep (1) print ('% s, % s' % (self. arg1, self. arg2, self. name, OS. getpid () for I in range (10): t = MyThread (I, I * ') t. start () print (t. count)

 

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.