Introduction to the first thread
Said Python thread, its encapsulation and methods are also more diverse, the use of more convenient. There are currently three main ways to do this.
1.1
Method One: Create a new thread by using a function in the thread module.
Note, however, that in version 3.4, the function is no longer in the thread module, to refer to the import
Import _dummy_thread. Its function to implement the source code:
Def start_new_thread (function, args, kwargs={}): "" "Dummy Implementation of _thread.start_new_thread (). Compatibility is maintained by making sure that "args" is a tuple and "Kwargs" is a dictionary. If An exception is raised and it's systemexit (which can be do by _thread.exit ()) It's caught and nothing is don E All other exceptions is printed out by using Traceback.print_exc (). If the executed function calls Interrupt_main the Keyboardinterrupt would be raised when the function returns. "" "If Type (args)! = Type (tuple ()): Raise TypeError (" 2nd Arg must be a tuple ") if Type (kwargs)! = Type (Dict () ): Raise TypeError ("3rd Arg must be a dict") global _main _main = False try:function (*args, **kwar GS) except Systemexit:pass except:import traceback traceback.print_exc () _main = True g Lobal _interrupt if _interrupt: _interrupt = False Raise Keyboardinterrupt
When used, for example:
def run (n): for I in Range (n): print (i) _dummy_thread.start_new_thread (run, (4,)) # Note the second parameter must be in the form of a tuple
1.2
Method two: Use threading. Thread runs the function directly in the thread.
It is defined in the threading module, and this example shows only a few of the important functions
Class Thread: "" A class that represents a Thread of control. This class can is safely subclassed in a limited fashion. There is ways to specify the Activity:by passing a callable object to the constructor, or by overriding the RU N () method in a subclass # .... def is_alive (self): #该函数返回当前线程是否存活状态, it's more important to be in a. #Return whether the thread is alive. def ident (self): #该函数返回当前线程的ID标示符, similar to Tid #Thread identifier of this Thread or None if it had not been started. This is a nonzero integer. def run (self): #该函数是线程的运行函数, overwrite overrides yourself, or make default calls directly. #Method representing the thread ' s activity. def start: #线程启动函数, the created thread does not start itself and must be started manually. #Start the thread ' s activity. def join (self, timeout=none): #该函数实现等待到运行结束, similar to synchronization, is also called thread merging because the thread ends #才运行下一行代码 after join, and the code instance is tested. #Wait until the thread terminates. def _wait_for_tstate_lock (self, Block=true, timeout=-1): #线程自身带了互斥锁 def Setdaemon (self): #设置线程属性状态, if set to True the main thread ends, The child thread isEnd, #若是False则必须等待到所有子线程结束, the main thread does not end the exit.
Import Threadingdef running (x, y): for I in range (x, y): print (i) for I in Range (3): T1 = Threading. Thread (Target=running, args= (1 * I, ten * (i + 1))) T1.start () t1.join ()
Using the Join method result
012345678912345678910111213141516171819234567891011121314151617181920212223242526272829
If not adopted, then the thread competes with irregular numbers, even duplicates, because there is no mutex
011234567892233456789101112131415161718192021222324252627282945678910111213141516171819
1.3
Method Three: By inheriting threading. Thread Creation Threads
Class Mz_thread (threading. Thread): Def __init__ (self, num): Threading. Thread.__init__ (self) self.num = num def run (self): while True:print (' I am ', self.num) For I in range: t = mz_thread (i) T.start ()
Results
I am 9I am 0I am 8I am 1I am 6I am 7I am 5I am 2I am 4I am 9I am 4I am 9I am 0I am 8I am 1I am 6I am 3I AM 4I am 9I am 0I am 8I am 7I am 5I am 2I am 4I am 9I am 0I am 8I am 1I am 6I am 3I am 7I am 7I am 5I am 2I am 4I am 9
Two implementations of the event class synchronize between threads
First look at the definition code of the event class
Class event: "" "Class implementing event objects. Events manage a flag that can is set to true with the set () method and reset to False with the clear () method. The wait () method blocks until the flag is true. The flag is initially false. "" "# After Tim Peters ' event class (without is_posted ()) def __init__ (self): Self._cond = Condition (Lock ()) Self._flag = False #很关键默认创建之后信号状态为False def _reset_internal_locks (self): # private! Called by Thread._reset_internal_locks-_after_fork () self._cond.__init__ () def is_set (self): #很关键, gets the current event signal status, returns A return value of true and false "" "return true if and only if the internal flag is true." " return Self._flag IsSet = Is_set def set (self): #很关键, set the event signal to a signal state "" "set the internal flag to true. All threads waiting for it to become true is awakened. Threads that call wait () once the flag is true would not be block at all. "" "Self._cond.acquire () Try: Self._flag = True Self._cond.notify_all () finally:self._cond.release () def clear (self ): #很关键, set the event signal to no signal status "" "Reset the internal flag to false. Subsequently, threads calling Wait () would block until set () is called to set the internal flag to true again. "" "self._cond.acquire () Try:self._flag = False finally:self._cond.release () def wait (self, timeout=none): #很关键, Sync signal wait function "" "Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set () to set the flag to true, or until the optional timeout OCC Urs. When the timeout argument was present and not None, it should was a floating point number specifying a timeout for th E operation in seconds (or fractions thereof). This method returns the internal flag on exit and so it would always return TRue except if a timeout is given and the operation times out. "" "self._cond.acquire () try:signaled = Self._flag if not signaled:si gnaled = self._cond.wait (timeout) return signaled finally:self._cond.release ()
Using event for synchronization, you must also create multiple event object arrays under multithreading.
Note that this Python array is defined and created dynamically.
Int_events_list = []for i in Range (3): int_events_list.append (Threading. Event ()) Int_events_list[0].set () #调用的时候也是采用下标索引方式实现.
Test synchronization Code
Class Mz_thread (threading. Thread): m_src = 0 m_des = 0 m_iindex = 0 def __init__ (self, numsrc, Numdes, IIndex): Threading. Thread.__init__ (self) self.m_src = numsrc Self.m_des = Numdes Self.m_iindex = IIndex def run ( Self): While self.m_src < self.m_des:int_events_list[self.m_iindex].wait () print (' I am t Hread ', Self.m_iindex, '--num--', self.m_src) int_events_list[self.m_iindex].clear () Int_events_lis t[(Self.m_iindex + 1)% 3].set () int_events_list = []thread_array = []if __name__ = = ' __main__ ': Print (' main THREAD Ru N: ', __name__) for I in Range (3): Int_events_list.append (Threading. Event ()) Int_events_list[0].set () for Ithreadindex in range (3): Thread_array.append (Mz_thread (Ithreadindex * 3, (Ithreadindex + 1) * 3, Ithreadindex)) Thread_array[ithreadindex].start ()
Results
I am Thread 0--num--0I am thread 1--num--3I am thread 2--num--6I am thread 0--num--0I am thread 1--num--3I AM Thread 2--num--6I am thread 0--num--0I am thread 1--num--3I am thread 2--num--6I am thread 0--num--0I am Thread 1--num--3I am thread 2--num--6I am thread 0--num--0I am thread 1--num--3I am thread 2--num--6I am T Hread 0--num--0I am thread 1--num--3I am thread 2--num--6I am thread 0--num--0I am thread 1--num--3I am THR EAD 2--num--6I am thread 0--num--0I am thread 1--num--3I am thread 2--num--6I am thread 0--num--0I am threa D 1--num--3I am thread 2--num--6I am thread 0--num--0I am thread 1--num--3I am thread 2--num--6I am Thread 0--num--0I am thread 1--num--3I am thread 2--num--6I am thread 0--num--0I am thread 1--num--3I am thread 2 --num--6I am Thread 0--num--0I am thread 1--num--3I am thread 2--num--6I am thread 0--num--0I am thread 1- -num--3I am Thread 2--num--6I am Thread 0--num--0I am thread 1--num--3I am thread 2--num--6
Three Instructions
The way in which Python synchronizes is used in addition to using event events, you can use queue queues directly. Because
The Python queues queue operation itself is encapsulated in the primitive language, enabling simultaneous access. You can also customize the flag
Or a related variable to access it. As for the thread mutex, the method is more. The next section will learn.
Python Personal Learning Note two