Today, read the fourth chapter of Python's core programming, multithreaded programming, and record the main points. 1. Process and thread processes are executing programs in which each process has its own address space, memory, data stacks, and other secondary data used to track execution. threads, which are actually executed under the same process, share the same context, and each thread in a process shares a piece of data space with the main thread, and information sharing and communication between threads is easier. 2. Use multithreaded Python with thread module and threading module
The core function of the thread module is Thread.start_new_thread (), which uses the example of the thread module.
Import thread
from time import CTime, sleep
loops = [4,2]
def loop (Nloop, Nsec, lock):
print ' Start loop ', Nloop, ' at: ', CTime (
nsec)
print ' Loop ', Nloop, ' do at: ', CTime ()
lock.release ()
def main (): C8/>print ' starting at: ', CTime ()
locks = []
nloops = range (len (loops)) for
i in Nloops:
lock = thread. Allocate_lock ()
lock.acquire ()
locks.append (lock) for
i in Nloops:
thread.start_new_thread ( Loop, (i, loops[i], locks[i])
for i-nloops:
while locks[i].locked (): Pass
print ' all do
at: ', c Time ()
if __name__ = = ' __main__ ':
Main ()
The Threading Module threading module, which supports daemon threads, compared to the thread module. The concept of a daemon can be understood so that if a thread is set as a daemon, it means that the thread is unimportant and the process exits without waiting for the thread to execute. If you want to set a thread as a daemon, you need to set Thread.daemon = True to use the thread class to create a multithreaded case before thread execution.
Import threading
from time to import sleep, CTime
class Mythread (threading. Thread): "" "DocString for Mythread" "
def __init__ (self, func, args, name="):
super (Mythread, self). __ init__ ()
self.name = name
Self.func = func
Self.args = args
def getresult (self): return
self.res< C10/>def Run (self):
self.res = Self.func (*self.args)
loops = [4,2]
def loop (Nloop, nsec):
print ' Start loop ', Nloop, ' at: ', CTime (
nsec)
print ' Loop done ', Nloop, ' in: ', CTime () return
' ws '
def main ():
print ' starting at: ', CTime ()
threads = []
nloops = range (len (loops)) for
I in Nloops:
#t = Threading. Thread (target = loop, args = (i, loops[i]))
t = Mythread (loop, (i,loops[i), loop.__name__)
threads.append (t) C26/>for i in Nloops:
Threads[i].start () for
i in Nloops:
threads[i].join ()
print threads[i]. GetResult ()
if __name__ = = ' __main__ ':
Main ()
3, synchronization primitives use synchronization, when using multiple threads, some specific functions or code blocks do not want to be executed concurrently by multiple threads.
#!/usr/bin/env python from atexit Import Register to random import Randrange from threading import Thread, Lock, Curren TThread from time import sleep, CTime class Cleanoutputset (set): Def __str__ (self): return ', '. Join (x for X In self) lock = lock () loops = (Randrange (2, 5) for x in Xrange (Randrange (3, 7)) remaining = Cleanoutputset () def Loop ( NSEC): MyName = CurrentThread (). Name Lock.acquire () remaining.add (myname) print ' [%s] started%s '% (CTime (), myname) #print ' [{0}] started {1} '. Format (CTime (), myname) Lock.release () sleep (nsec) Lock.acquire () r
Emaining.remove (myname) print ' [%s] Completed%s (%d secs) '% (#print ' [{0}] Completed {1} ({2} secs) '. Format ( CTime (), myname, nsec) print ' (Remaining:%s) '% (remaining or ' NONE ') #print ' (remaining: {0}) '. Format (Rema ining or ' NONE ') lock.release () def _main (): For pause in Loops:thread (Target=loop, args=,). Start () @register def _atexiT (): print ' All do at: ', CTime () if __name__ = = ' __main__ ': _main ()
Multiple types of synchronization primitives supported by Python, including lock/mutex, semaphore use lock, call Lock.require () function fetch lock, call Lock.release () function release lock