Python Beginner's path: Python basics-threads, processes, co-routines

Source: Internet
Author: User
Tags for in range mutex

The previous section provides a simple introduction to threads and processes, and describes the Gil mechanism in Python. This section details the concepts and implementations of threads, processes, and co-routines.

Thread Basic usage

Method 1: Create a threading. The thread object that passes the callable object as a parameter in its initialization function (__INIT__)

Import Threadingimport timedef worker ():    time.sleep (2)    print ("  Test") for in range (5):    = Threading. Thread (target=worker)    T.start ()
thread Creation Method 1

Method 2: override the Run method by inheriting the thread class

 import   threading  class   MyThread (threading. Thread):  def  __init__   (self, func, args): Self.func  = Func self.args  = args super (MyThread, self).  __init__   ()  def   Run (self): Self.func (Self.args)  def   F2 ( ARG):  print   = MyThread ( F2, 123) Obj.start ()  
Thread Creation Method 2Thread Lock

In the top 2 examples of creating multithreading, there is no relationship between multiple threads. Suppose such a situation, there is a global count num, each thread gets this global count, does some processing based on NUM, and then adds Num 1. It's easy to write code like this:

ImportThreadingImportTimenum=0classMyThread (Threading. Thread):defRun (self):GlobalNum Num+ = 1Time.sleep (0.5) msg= self.name+'Set num to'+Str (NUM)Print(msg)if __name__=='__main__':     forIinchRange (5): T=MyThread () T.start () Out:thread-5 Set num to 2Thread-3 Set num to 3Thread-2 Set num to 5Thread-1 Set num to 5Thread-4 Set num to 4

The problem arises because there is no control over the access of multiple threads to the same resource, causing damage to the data and making the results of the thread run unpredictable. This behavior is called "Thread insecurity." So there is the concept of the thread lock.

Thread synchronization ensures that multiple threads secure access to competing resources, and the simplest synchronization mechanism is to introduce mutexes . A mutex introduces a state to a resource: locked/non-locked. When a thread changes the shared data, it locks it, the state of the resource is locked, the other thread cannot be changed, and until the thread frees the resource, the state of the resource becomes "non-locked", and the other thread can lock the resource again. The mutex ensures that only one thread is written at a time, thus guaranteeing the correctness of the data in multi-threaded situations.

Producer, consumer model

Extension: Custom thread pool

Process Basic Use

Process Lock

Inter-process data sharing

Use of process pools

The concept of co-process

Realize

Python Beginner's path: Python basics-threads, processes, co-routines

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.