A thread is the smallest unit that the operating system can perform operations on. It is included in the process and is the actual operating unit of the process. A thread refers to a single sequential control flow in a process in which multiple threads can be concurrent and each thread performs different tasks in parallel.
Using the Threading module
Method One:
import threadingimport timedef foo(n): print(‘foo %s‘%n) time.sleep(1) print(‘end foo‘)def bar(n): print(‘bar %s‘%n) time.sleep(2) print(‘end bar‘)t1 = threading.Thread(target=foo, args=(1,))t2 = threading.Thread(target=bar, args=(2,))t1.start()t2.start()print(‘........in the main..........‘)运行结果:foo 1bar 2........in the main..........end fooend bar
Method Two:
import time, threadingclass MyThread(threading.Thread): def __init__(self, num): threading.Thread.__init__(self) self.num = num def run(self): #定义线程要运行的函数 print("running on number:%s" % self.num) time.sleep(3)if __name__ == ‘__main__‘: t1 = MyThread(1) t2 = MyThread(2) t1.start() t2.start()运行结果:running on number:1running on number:2
The join method causes the main thread to wait for the child thread to finish before continuing
import threadingimport timebegin = time.time()def foo(n): print(‘foo %s‘%n) time.sleep(1) print(‘end foo‘)def bar(n): print(‘bar %s‘%n) time.sleep(2) print(‘end bar‘)t1 = threading.Thread(target=foo, args=(1,))t2 = threading.Thread(target=bar, args=(2,))t1.start()t2.start()t1.join()t2.join()print(‘........in the main..........‘)运行结果:foo 1bar 2end fooend bar........in the main..........
Serial vs. multithreading in compute-intensive tasks
import threading, timebegin = time.time()def add(n): sum = 0 for i in range(n): sum += i print(sum)add(100000000)add(200000000)end = time.time()print(end-begin)运行结果:49999999500000001999999990000000017.66856598854065import threading, timebegin = time.time()def add(n): sum = 0 for i in range(n): sum += i print(sum)t1 = threading.Thread(target=add, args=(100000000,))t1.start()t2 = threading.Thread(target=add, args=(200000000,))t2.start()t1.join()t2.join()end = time.time()print(end-begin)运行结果:49999999500000001999999990000000021.088160276412964# 结果为串行运行比多线程运行更快
Cpython has the GIL (Global interpreter lock, the Universal interpreter lock), so at the same time, only one thread can enter the schedule. If the task is IO-intensive, multithreading can be used, and if the task is computationally intensive, the best method is to change to C. Setdaemon ()
Call this method as long as the main thread is complete, regardless of whether the child thread is complete and exit with the main thread.
Threading.currentthread ()
Returns the current thread variable.
Threading.active_count ()
Returns the number of threads that are running.
Import threading, Timefrom time import ctime,sleepdef Music (func): Print (Threading.current_thread ()) for I in range ( 2): Print ("Begin listening to%s.%s"% (func, CTime ())) sleep (2) print ("End Listening%s"%ctime ()) de F Movie (func): Print (Threading.current_thread ()) for I in Range (2): Print ("Begin watching at the%s%s"%{fun C, CTime ()}) sleep (4) print ("End watching%s"%ctime ()) threads = []T1 = Threading. Thread (Target=music, args= (' Klvchen ',)) threads.append (t1) t2 = Threading. Thread (Target=movie, args= (' Lili ',)) Threads.append (t2) If __name__ = = ' __main__ ': for T in Threads:t.setdaemon (t Rue) T.start () print (Threading.current_thread ()) print (Threading.active_count ()) print ("All over%s"%ctim E ()) Operation result: <thread (Thread-1, started daemon 5856) >begin listening to Klvchen. Wed Jul 23:43:51 2018<thread (Thread-2, started daemon 9124) ><_mainthread (Mainthread, started 9444) >3all Over Wed Jul 11 23:43: 51 2018
Python Threads and processes