Python Thread, Process

Source: Internet
Author: User
Tags thread stop

Threading is used to provide thread-related operations, and threads are the smallest unit of work in an application

Calling Threads directly

#!/usr/bin/env python#-*-coding:utf-8-*-__author__='Administrator'ImportThreadingImport TimedefSayhi (num):#define the functions to be run by each thread    Print("running on number:%s"%num) time.sleep (3)if __name__=='__main__': T1= Threading. Thread (target=sayhi,args= (1,)) T2= Threading. Thread (target=sayhi,args= (1,)) T1.start ()#Start ThreadT2.start ()#start another thread    Print(T1.getname ())#Get thread name    Print(T2.getname ())

How do I do a for loop if I need to open 10 threads?

#!/usr/bin/env python#-*-coding:utf-8-*-__author__='Administrator'ImportThreadingImport TimedefSayhi (num):#define the functions to be run by each thread    Print("running on number:%s"%num) time.sleep (3)if __name__=='__main__':     forIinchRange (10): T= Threading. Thread (target=sayhi,args=(i,)) T.start ()

Inherited calls

#!/usr/bin/env python#-*-coding:utf-8-*-__author__='Administrator'ImportSocketserverImportThreadingImport TimeclassMythread (Threading. Thread):def __init__(self,num): Threading. Thread.__init__(self) self.num=NumdefRun (self):#define the functions to be run by each thread        Print("running on number:%s"%self.num) Time.sleep (3)if __name__=='__main__': T1= Mythread (1) T2= Mythread (2) T1.start () T2.start ()

More ways:

      • Start thread is ready to wait for CPU scheduling
      • SetName setting a name for a thread
      • GetName Get thread Name
      • Setdaemon set to background thread or foreground thread (default)
        If it is a background thread, during the main thread execution, the background thread is also in progress, and after the main thread finishes executing, the background thread stops regardless of success or not.
        If it is the foreground thread, during the main thread execution, the foreground thread is also in progress, and after the main thread finishes executing, wait for the foreground thread to finish, the program stops
      • The join executes each thread one by one and continues execution after execution, making multithreading meaningless
      • The Run method that executes the thread object automatically after the run thread is dispatched by the CPU

Join & Daemon

#!/usr/bin/env python#-*-coding:utf-8-*-__author__='Administrator'Import TimeImportThreadingdefrun (n):Print('[%s]------running----\ n'%N) time.sleep (2)    Print('--done--')defMain (): forIinchRange (5): T= Threading. Thread (target=run,args=[I,])#time.sleep (1)T.start ()#t.join (1)        Print('Starting thread', T.getname ()) m= Threading. Thread (target=main,args=[])#M.setdaemon (True) #将主线程设置为Daemon线程, when it exits, the other child threads exit at the same time, regardless of whether the task is completed or notM.start ()#M.join (timeout=10)Print("---main thread done----")

Thread Lock

A process can play multiple processes, multiple threads share the memory space of the parent process, which means that each thread can access the same data, at this point, if 2 threads simultaneously

What happens if you want to modify a piece of data?

Since the threads are randomly dispatched, and each thread may execute only n execution, the CPU then executes other threads. So the following issues occur

#!/usr/bin/env python#-*-coding:utf-8-*-ImportThreadingImportTimegl_num=0defShow (ARG):Globalgl_num Time.sleep (1) Gl_num+=1PrintGl_num forIinchRange (10): T= Threading. Thread (Target=show, args=(i,)) T.start ()Print 'Main thread Stop'
Lock not used

After locking

#!/usr/bin/env python#Coding:utf-8   ImportThreadingImportTime Gl_num=0 Lock=Threading. Rlock ()defFunc (): Lock.acquire ()GlobalGl_num Gl_num+=1Time.sleep (1)    Printgl_num lock.release () forIinchRange (10): T= Threading. Thread (target=Func) T.start ()
after the lock is added

Import TimeImportThreadingdefaddnum ():GlobalNum#get this global variable in each thread    Print('--get Num:', num) time.sleep (1) Num-=1#perform a-1 operation on this common variableNum= 100#set a shared variableThread_list = [] forIinchRange (100): T= Threading. Thread (target=addnum) T.start () thread_list.append (t) forTinchThread_list:#wait for all threads to finish executingT.join ()Print('Final num:', num)
not locked
Import TimeImportThreadingdefaddnum ():GlobalNum#get this global variable in each thread    Print('--get Num:', num) time.sleep (1) Lock.acquire ()#lock before modifying dataNum-=1#perform a-1 operation on this common variableLock.release ()#Release after modificationNum= 100#set a shared variableThread_list =[]lock= Threading. Lock ()#generate a global lock forIinchRange (100): T= Threading. Thread (target=addnum) T.start () thread_list.append (t) forTinchThread_list:#wait for all threads to finish executingT.join ()Print('Final num:', num)
after the lock is added

Normally, this num result should be 0, but in Python 2.7 run more than a few times, you will find that the final printout of the NUM result is not always 0, why each run the result is different? Ha, very simple, if you have a A, a, two threads, at this time to the NUM to reduce the 1 operation, because 2 threads are concurrently running concurrently, so 2 threads are likely to take the num=100 this initial variable to the CPU to calculate, when a thread to end the result is 99, But at this point the result of the B-thread operation is also 99, two threads at the same time the result of the CPU operation is assigned to the NUM variable, the result is 99. What about that? It is very simple that each thread will modify the data in order to avoid having to modify it when it is not finished, so you can add a lock to the data so that other threads will have to wait for you to modify the data and release the lock before accessing the data.

* Note: Do not run on the 3.x, do not know why, the results on 3.x is always correct, may be automatically added lock

Python Thread, Process

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.