Python core Programming Note----threading

Source: Internet
Author: User

Each thread in a process shares the same piece of data space, so the threads can more easily share data and communicate with each other than between processes.

1. Global interpreter Lock (GIL)

The Python interpreter can "run" multiple threads, but at any point, only one thread runs in the interpreter.
In a multithreaded environment, the Python virtual machine (interpreter) executes as follows:
1). Set GIL
2). Switch to a thread to run
3). Run:
A. Specify the number of bytecode directives, or
B. Thread active Surrender control (can call Time.sleep (0))
4). Set the thread to sleep
5). Unlock GIL
6). Repeat all of the above steps again

2. Exit the Thread

When a thread ends the calculation, it exits. A thread can call an exit function such as thread.exit () or use Python to exit a process's standard method, such as sys.exit () or throwing a systemexit exception. However, you may not directly "kill" a thread.

3.Python Threading Module

The thread and threading modules allow programmers to create and manage threads.
The thread module provides basic threading and lock support, while threading provides a higher level of functionality for more powerful thread management.
The queue module allows a user to create a data structure that can be used to share information between multiple threads.

4.threading Module

Threading Module Object Description
Thread represents an object that executes on a thread
Lock lock Primitive Object (same as lock object in thread module)
Rlock can re-enter the lock object. Enables a single thread to obtain the acquired lock again (recursive locking).
The Condition condition variable object allows one thread to stop waiting for the other thread to satisfy a certain condition. For example, change of state or change in value.
The condition variable that is common to the Event. Multiple threads can wait for an event to occur, and all threads will be activated after the event.
Semaphore provides a "waiting room" structure for the thread that waits for the lock
Boundedsemaphore is similar to Semaphore, except that it is not allowed to exceed the initial value
The Timer is similar to thread, except that it waits a while before it starts to run

The thread class in threading is the main running object

Function
Describe
Start () starts the execution of the thread
Run () A function that defines the functionality of the thread (typically overridden by a quilt class)
The Join (Timeout=none) program hangs until the thread ends, and if timeout is given, it blocks timeout seconds
GetName () returns the name of the thread
SetName (name) sets the name of the thread
The IsAlive () Boolean flag that indicates whether the thread is still running
Isdaemon () returns the thread's daemon flag (daemon flag)
Setdaemon (daemonic) sets the daemon flag of the thread to Daemonic (be sure to call before the start () function is called)

1 ImportThreading2  fromTimeImportSleep, CTime3 4loopn=[2,4]5 6 7 defLoop (nloop,nsec):8     Print "Loop"+str (Nloop) +"start at:"+CTime ()9 Sleep (nsec)Ten     Print "Loop"+str (Nloop) +"stop at:"+CTime () One  A      - defMain (): -     Print "start at"+CTime () theThread=[] -      forIinchRange (len (LOOPN)): -T=threading. Thread (target=loop,args=(I,loopn[i])) - thread.append (t) +#start, the thread that executes when the join executes here runs until the end of the second thread. -      forIinchRange (len (LOOPN)): + Thread[i].start () A          at      forIinchRange (len (LOOPN)): - Thread[i].join () #If you have other things to do (such as processing or waiting for other client requests) besides waiting for the thread to end, you do not need to call join (), only call join () If you want to wait for the thread to end.
 -     Print "  "+CTime (                )  If__name__'__main__':     Main ()

Eg: after all the threads have been created, call the start () function together to start, instead of creating a startup one.

The role of Join ():

Once the thread is started, it runs until the thread's function ends and exits. prevents the child thread from ending when the main thread is finished


5. Producer-Consumer issues and Queue modules


Function description
Queue module functions
Queue (size) to create a queue object of size
Queue Object Functions
Qsize () returns the size of the queue (this value is approximate because the queue may be modified by another thread when it returns)
Empty () returns True if the queue is null, otherwise False
Full () returns False if the queue returns True
Put (item,block=0) puts the item in the queue, and if a block (not 0) is given, the function will block until there is space in the queue
Get (Block=0) takes an object from the queue, and if a block (not 0) is given, the function will block until there are objects in the queue

ImportThreading fromQueueImportQueue fromTimeImportSleep,ctimeImportRandomclassMyThread (Threading. Thread): #threading另一种用法: Inherit threading. Thread class, overwrite the Run function def __init__(self,func,args,name="'): Threading. Thread.__init__(self) self.name=name Self.func=func Self.args=argsdefRun (self):Print "Start"+self.name+"at ;"+CTime () apply (Self.func,self.args)Print "Stop"+self.name+"at ;"+CTime ()defWriteq (Queue): Queue.put ("Item", 1)    Print "Product object for Q. Now size:", Queue.qsize ()defREADQ (Queue): Queue.get (1)    Print "consumed object from Q. Now size:", Queue.qsize ()defwriter (queue,n): forIinchrange (N): Writeq (queue) sleep (Random.randint (1,3))        defReader (queue,n): forIinchrange (N): READQ (queue) sleep (Random.randint (3,5)) Funcs=[Writer,reader]nfuncs=Len (funcs)defMain (): Queue=queue (15) n=random.randint (4,7) Thread=[]         forIinchRange (Nfuncs): t=mythread (funcs[i],args= (Queue,n), Name=funcs[i].__name__) thread.append (t) forIinchRange (Nfuncs): Thread[i].start () forIinchRange (Nfuncs): Thread[i].join ()Print " All done"if __name__=='__main__': Main ()

Operation Result:

Start writer at; Tue June 13 21:58:23 2017start reader at; Tue June13 21:58:23 2017Product Object forQ. Now size:0 consumed Object fromQ. Now Size:1Product Object forQ. Now Size:1Consumed Object fromQ. Now Size:0product object forQ. Now Size:1Product Object forQ. Now Size:2Product Object forQ. Now Size:3Consumed Object fromQ. Now Size:2Product Object forQ. Now Size:3Product Object forQ. Now Size:4Consumed Object fromQ. Now Size:3stop writer at; Tue June13 21:58:37 2017Consumed Object fromQ. Now Size:2Consumed Object fromQ. Now Size:1Consumed Object fromQ. Now size:0stop reader at; Tue June13 21:58:50 2017 All done

Python core Programming Note----threading

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.