threading库可用来在单独的线程中执行任意的python可调用对象。尽管此模块对线程相关操作的支持不够,但是我们还是能够用简单的线程来处理I/O操作,以减低程序响应时间。
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | from threading import Thread import time def countdown(n): while n > 0 : print ( 'T-minus:' , n) n - = 1 t = Thread(target = countdown, args = ( 10 ,)) t.start() # 开启线程 time.sleep( 2 ) if t.is_alive() is True : print ( "停止线程..." ) t._stop() # 停止线程 |
start函数是用来开启线程的,_stop函数是用来停止线程的。为了防止在线程中进行I/O操作时出现阻塞等问题,运行一段时间之后,可以判断线程是否还存活,如果线程还存在就调用_stop()停止,防止阻塞(你可以将_stop函数封装到类中,我这里并没有这么做)。
当然,你可以调用ThreadPool线程池来处理,而不是手动创建线程。如果线程间不需要共享变量的话,使用线程还是很方便的,可以减少很多的麻烦操作以及省时。如果需要在线程间进行通信,我们可以使用队列来实现:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | from queue import Queue from threading import Thread class kill: def terminate( self , t): if t.isAlive is True : t._stop() def product(out_q): for i in range ( 5 ): out_q.put(i) def consumer(in_q): for i in range ( 5 ): print (in_q.get()) q = Queue() t1 = Thread(target = consumer, args = (q,)) t2 = Thread(target = product, args = (q,)) t1.start() t2.start() k = kill() # 查询线程是否终止,防止阻塞... k.terminate(t1) k.terminate(t2) |
Queue实例会被所有的线程共享,同时它又拥有了所有所需要的锁,因此它们可以安全的在任意多的线程中共享。在这里要注意,不要再多线程中使用除了put(),get()方法之外的queue类的方法,因为在多线程环境中这是不可靠的!对于简单的小型的线程中数据的通信,可以使用队列来处理。如果是大型的数据需要交互通信,python提供了相关的模块你可以使用,具体的u need baidu.
所谓协程,其实就是在单线程的环境下的yield程序。
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | from collections import deque def countdown(n): while n > 0 : print ( "T-minus" , n) yield # 返回之后下次直接从这里执行...相当于C#里面得yield return . n - = 1 print ( "this is countdown!!!" ) def countup(n): x = 0 while x < n: print ( "Counting up" , x) yield x + = 1 class TaskScheduler: def __init__( self ): self ._task_queue = deque() def new_task( self , task): self ._task_queue.append(task) def run( self ): while self ._task_queue: task = self ._task_queue.popleft() try : next (task) self ._task_queue.append(task) except StopIteration: pass sche = TaskScheduler() sche.new_task(countdown( 10 )) sche.new_task(countdown( 5 )) sche.new_task(countup( 15 )) sche.run() |
来源: http://www.92to.com/bangong/2017/07-11/25043936.html