1. multithreading
from threading import Thread import time def func(n): time.sleep(1) print(n) for i in range(10): T = the Thread (target = FUNC, args = (I,)) # register functions into sub-thread, and pass parameters t.start () # promoter thread
result:
2. Another way to start a multi-threaded
from threading import Thread import time class MyTread (the Thread): DEF the __init__ (Self, Arg): # reception parameters . Super () the __init__ () self.arg = arg DEF RUN (Self): # contents of sub-thread to perform the time.sleep (1 ) Print (self.arg) for i in range(10): T = MyTread (I) # instantiating subunit thread passed parameters + t.start () # promoter thread
result:
3. Check whether multi-threaded process are the same inside
from threading import Thread import time import os class MyTread (the Thread): DEF the __init__ (Self, Arg): # reception parameters . Super () the __init__ () self.arg = arg DEF RUN (Self): # contents of sub-thread to perform the time.sleep (1 ) Print (self.arg, os.getpid ()) for i in range(10): T = MyTread (I) # instantiating subunit thread passed parameters + t.start () # promoter thread Print ( ' main thread: ' , os.getpid ())
Result: The same process number, a description of all the threads inside the same process.
4. The data sharing between threads
from threading import Thread import time ggg = 100 def func(n): time.sleep(1) global ggg GGG = 0 Print ( ' child thread: ' , n-) t_list = [] for i in range(10): t = Thread(target=func,args=(i,)) t.start() t_list.append(t) for i in t_list: i.join() Print ( ' main thread: ' , GGG)
Results: The global variable ggg could have been 100, was changed to 0 in the sub-thread.