Thread base
# -Thread basis . "" " Multi-tasking concept: that the operating system can run multiple tasks concurrently: refers to the number of excess cpu audit task, task scheduling algorithm through a variety of operating systems, with multiple tasks to achieve" together " execution (in fact, there are always some tasks are not performed because the task switching speed is quite fast, it seems to perform together) parallel: refers to the number of tasks is less than equal to the number of cpu core that task really is carried out with the python module thread is a relatively low-level module, python's threading is an advanced module common operations threading.currentThread (): returns the current thread variable. threading.enumerate ():. returns a running thread that contains the list after running threads from start to end ago, excluding the thread before starting and after the termination of threading.activeCount (): returns the number of threads running, and len (threading.enumerate ()) have the same result run (): method to indicate active threads start ( ): start the thread activity join ([time]): wait until the thread abort it blocks the calling thread until the thread's join () method is called suspended. - normal exit or throw an unhandled exception - or the optional timeout occurs isAlive (): Returns the thread is active getName (): Returns the thread name setName (): Set the thread name thread Precautions when using the threading module, tend to define a the new sub-class of class, just inherit threading.Thread on it, then override the run method when the thread ends run () method thread to complete. The execution order of multithreaded programs is uncertain beyond the control of the thread scheduler, but can be influenced by the way the thread scheduling otherwise. Each thread has a default name, python automatically assigns a name for the thread all the threads in a process of shared global variables, it is easy to share data among multiple threads threads are then free to change global variables between multiple threads may cause confusion of global variables (ie, non-thread-safe) If multiple threads to the same global variable operation, there will be resource contention problems, so that the data results incorrectly synchronized pace is collaborative, and operated according to predetermined priorities. Such as: Are you finished, I say. Understood as processes or threads with an A and B, have to rely to a certain extent when A performs a result of B, then stopped, motioned run B; B execution, then the result to A; A before proceeding. Thread synchronization when multiple threads simultaneously modify almost certain shared data, the need to synchronize control the use of Thread objects Lock and Rlock can achieve a simple thread synchronization, the two objects have acquire method and release method for those who require each and allow only one thread operation, the operation can be put between acquire and release methods thread synchronization ensures secure access to multiple threads compete for resources, the most simple synchronization mechanism is introduced mutex when a thread to change the shared data , the first of its lock, and the status of the resource is "locked", other threads can not be changed; Until the thread to release resources, state resources into a "non-locking", other threads can lock the resource again. Mutex to ensure that only one thread is written, so as to ensure the correctness of the data of multiple threads. hreading Lock module defines the class, you can easily handle lock # create lock mutex = threading.Lock () # locked mutex.acquire () # release mutex.release () the benefits of certain key lock ensures that the code only by a thread from start to finish to complete the implementation of the lock prevents harm multi-threaded execution may cause a deadlock deadlock share resources among multiple threads of time, if two threads each occupy a portion of the resources and at the same time waiting for each other's resources, will cause a deadlock to avoid deadlock should be avoided (banker's algorithm) program designed to add timeout, etc. "" " # multithreading way to create a Import threading # threading.Thread (target = function) to pass the name DEF say (): Print ( " Hello, Python " ) for i inthe Range (5 ): tThreading.Thread = (target = say) t.start () # when calling start (), will really create a thread and starts executing # main thread will wait for the end after the end of all child threads Import Threading from Time Import SLEEP, the ctime DEF sing (): for I in Range (. 3 ): Print ( " is singing% D ... " % I) SLEEP ( . 1 ) DEF Dance (): for I in Range (. 3 ): Print ( " % d is dancing ..." %I) SLEEP ( . 1 ) IF the __name__ == ' __main__ ' : Print ( ' --- Start ---: S% ' % the ctime ()) T1 = of the threading.Thread (target = Sing) T2 = of the threading.Thread (target = Dance) t1.start () t2.start () SLEEP ( 5) # block this line of code, give it a try, whether the program will immediately end? Print ( ' --- end ---:% S ' % ctime ()) # View the number of threads Import Threading from TimeImport SLEEP, the ctime DEF Sing (): for I in Range (. 3 ): Print ( " is singing% D ... " % I) SLEEP ( . 1 ) DEF Dance (): for I in Range (. 3 ): Print ( " dancing% D ... " % I) SLEEP ( . 1 ) IF the __name__ == ' __main__ ' : Print ( ' --- start ---:% S ' % the ctime ()) T1 = of the threading.Thread (target = Sing) T2 = of the threading.Thread (target = Dance) t1.start () t2.start () alength = threading.activeCount () Print ( " the number of active threads is:% S " % alength) the while True: # length = len (threading.enumerate ()) # returns a list that contains a list of running threads of the # Print the number of threads ( 'run for :% D 'length%) # IF length <=. 1: # BREAK alength = threading.activeCount () Print( " Number of active threads is:% S " % alength) # number of threads running return threading.activeCount () == len (threading.enumerate ()) IF alength <=. 1 : BREAK SLEEP ( 0.5 ) # execution of a thread order can not be determined Import Threading Import Time class the MyThread (of the threading.Thread): DEF RUN (Self): for I in Range (. 3 ): the time.sleep ( . 1 ) MSG = " the I'm " + the self.name + ' @ '+str(i) print(msg) def test(): for i in range(5): t = MyThread() t.start() if __name__ == '__main__': test() # 线程执行代码的封装 import threading import time class MysThread(threading.Thread): def run(self): for i in range(3): time.sleep(1) MSG= " The I'm " + self.name + ' @ ' + str (i) # save the name attribute is the name of the current thread Print (msg) IF __name__ == ' __main__ ' : t = MysThread () t.start () # multithreaded data is shared from Threading Import the thread Import Time g_num = 100 DEF WORK1 (): Global g_num for I in Range (. 3 ): g_num + =. 1 ( Print " ---- in WORK1, g_num IS% d --- " % g_num) DEF WORK2 (): , Ltd. Free Join g_num Print ( " ---- in WORK2, g_num IS% d --- " % g_num) Print ( " before --- thread creation% d --- iS g_num " % g_num) t1 = the thread (target = WORK1) t1.start () # delay for a while to ensure t1 thread things done time.sleep (1 ) T2 = the Thread (target = WORK2) t2.start () # mutex - to solve the problem of data sharing occurs Import Threading Import Time g_num= 0 def test1(num): global g_num for i in range(num): mutex.acquire() # 上锁 g_num += 1 mutex.release() # 解锁 print("---test1---g_num=%d"%g_num) def test2(num): global g_num for i in range(num): mutex.acquire() # 上锁 g_num += 1 mutex.release() # 解锁 print(" --- --- g_num test2 =% d " % g_num) # create a mutex # default state is unlocked mutex = threading.Lock () # create two threads, each of them plus one million g_num times P1 of the threading.Thread = (target = test1, args = (1000000 ,)) p1.start () P2 = of the threading.Thread (target = test2, args = (1000000 ,)) p2.start () # wait calculation is completed while len (threading.enumerate ()) =. 1! : the time.sleep ( . 1 ) Print ( " final result after the two threads of the same global variable operation is:% S " % g_num) # UDP chat importSocket Import Threading # receiving information DEF RECVS (UDP_SOCKET): the while True: Back = udp_socket.recvfrom (1024 ) MSG = Back Print (MSG) # Send DEF SENDS (UDP_SOCKET, DEST_IP, dest_port): the while True: MSG = INPUT ( " Please enter the information you want to send: " ) IF msg == ' Exit ' : BREAK udp_socket.sendto (msg.encode (), (DEST_IP, dest_port)) # udp主函数 def main(): udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udp_socket.bind(('', 8001)) dest_ip = input("请输入对方的ip:") dest_port = int(input("请输入对方的port:")) t1 = threading.Thread(target=sends, args=(udp_socket, dest_ip, dest_port)) t2 = threading.Thread(target=recvs, args=(udp_socket,)) t1.start() t2.start() if __name__ == '__main__': main()