Python实现的EventLoop

EventLoop

vim EventLoop.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
 
import threading
import Queue
import time
import random

mainThread = threading.currentThread()
print "%s: start\n" % mainThread.getName()

# 队列&同步
mainThreadQueue = Queue.Queue()
mainThreadSemaphore = threading.Semaphore(value=0)

# 子线程
def subThreadRun():
    while(1):
        time.sleep(1)
        
        seeds = "abcd"
        count = random.randint(2, 4)
        
        for _ in range(count):
            data = random.choice(seeds)
            mainThreadQueue.put(data)
            print "%s: put %s" % ((threading.currentThread().getName()), data)
        
        print "%s: awake %s\n" % (threading.currentThread().getName(), mainThread.getName())
        mainThreadSemaphore.release()
        
        exit(0)
threading.Thread(target = subThreadRun, name = "SubThread").start()

# 主线程
def mainThreadRun():
    while(1):
        if mainThreadQueue.empty():
            print "%s: sleep\n" % threading.currentThread().getName()
            mainThreadSemaphore.acquire()
        else:
            print "%s: get %s" % ((threading.currentThread().getName()), mainThreadQueue.get())
mainThreadRun()

print "%s: terminate" % mainThread.getName()
  • 测试
python EventLoop.py
MainThread: start

MainThread: sleep

SubThread: put a
SubThread: put b
SubThread: put a
SubThread: put d
SubThread: awake MainThread

MainThread: get a
MainThread: get b
MainThread: get a
MainThread: get d
MainThread: sleep

关键

  • Event: Event Queue

  • Loop: 循环处理Queue中的Event

  • 通信: 操作Event Queue

  • 同步: 信号量或其它机制(例如: 锁)

互动

上述线程blocking模型有何缺点? 如何克服?

参考

  • 计算机的心智 -- 操作系统之哲学原理

  • 17.1. threading — Thread-based parallelism

你可能感兴趣的:(Python实现的EventLoop)