### 显示并发进程的例子 import threading from threading import Thread, Timer import time ##### 基于一个函数建立两个线程对象并激活它们 ##def myfunc(s): ## n = 0 ## for i in range(1000000): ## n += i ## print(str(n) + ", " + s) ## ##th1 = Thread(target=lambda:myfunc("Fun call 1.\n")) ##th2 = Thread(target=lambda:myfunc("Fun call 2.\n")) ##th1.start() # 激活线程对象 ##th2.start() # 激活线程对象 ##print("Last statement of the main.\n") ##### 基于一个函数建立两个线程对象并激活它们,最后等它们结束 ##def myfunc(s): ## n = 0 ## for i in range(10000000): ## n += i ## print(str(n) + ", " + s) ## ##th1 = Thread(target=lambda:myfunc("Fun call 1.\n")) ##th2 = Thread(target=lambda:myfunc("Fun call 2.\n")) ##th1.start() # 激活线程对象 ##th2.start() # 激活线程对象 ##print("Start two threads. Wait to their terminations.") ##for th in threading.enumerate(): ## print(th.getName() + ":", ## "Alive" if th.is_alive() else "Not Alive") ##th1.join() ##print("Thread 1 is terminated.") ##th2.join() ##print("Thread 2 is terminated.") ##print("Last statement of the main.\n") ##### th1.start() # 一个线程对象只能run一次,再start出错 ##### 从Thread派生定义新线程类,重新定义 __init__ 和 run 方法 ##class MyThread(Thread): ## def __init__(self): # 用name关键字给定进程名 ## Thread.__init__(self, name="the sub thread") ## ## def run(self): ## print("The sub-tread is running\n") ## time.sleep(3.0) # 使用time包的功能睡眠 3 秒 ## self.prt() ## ## def prt(self): ## print("Hello, I am {}\n".format(self.getName())) ## ##process = MyThread() ##process.start() ##print("I am the main thread.\n") ##print("The sub thread is active:", process.is_alive()) ### 在run里启动一个Timer计时线程 ##class MyThread1(Thread): ## def __init__(self): ## Thread.__init__(self, name = "sub thread 1") ## ## def run(self): ## print("The sub-tread starts\n") ## t = Timer(3.0, self.prt) ## print("Start the Timer\n") ## t.start() ## ## def prt(self): ## print("Hello, I am the {}\n".format(self.getName())) ## print("I am resumed now.\n") ## print("I terminates\n") ## ##process = MyThread1() ##process.start() ##print("I am the main thread.\n") ##time.sleep(5.0) ##print("The sub thread is alive?", process.is_alive()) ##### 创建同一线程类的多个线程并让它们运行 ##class Th1(Thread): ## _num = 0 ## ## def __init__(self): ## Thread.__init__(self, name="sub-thread") ## self.setName(self.getName() + "_" + str(Th1._num)) ## Th1._num += 1 ## ## def run(self): ## for i in range(4): ## n = 0 ## for j in range(100000): ## n += j ## print("{}:{}: {}\n".format( ## self.getName(), str(i), str(n))) ## print(self.getName() + " terminated.\n") ## ##for n in range(4): ## th = Th1() ## th.start() ##print("Main finished.\n") #### 展示并发程序相对执行速度的非确定性 ##def fprint(s): ## print(s) ## ##class SubPrint(Thread): ## def __init__(self, s): ## Thread.__init__(self, name = "sub thread 1") ## self._s = s ## ## def run(self): ## for i in range(10): ## t = Timer(0.2, lambda: fprint(self._s)) ## t.start() ## ##process = SubPrint("I am the sub thread.\n") ##process.start() ##for i in range(10): ## t = Timer(0.2, lambda: fprint("I am main thread.\n")) ## t.start() #### 两个线程操作同一个全局变量 #### 说明进程之间合作可能出现的情况 ##num = 0 ## ##class Adder(Thread): ## def __init__(self, name_): ## Thread.__init__(self, name=name_) ## ## def run(self): ## global num ## for i in range(1000000): ## num = num + 1 ## ##th1 = Adder("Adder1") ##th1.start() ##th1.join() # 等待Adder1结束 ##th2 = Adder("Adder2") ##th2.start() ##th2.join() # 等待Adder2结束 ##print("Result:", num) ###### 两个线程对操作同一个全局变量,用Lock保护共享变量 ###### Lock对象符合context manager的要求,用with很方便 ##from threading import Lock ##lock1 = Lock() ##num = 0 ## ##class Adder(Thread): ## def __init__(self, name_): ## Thread.__init__(self, name=name_) ## ## def run(self): ## global num ## for i in range(1000000): ## with lock1: ## num = num + 1 ## ##th1 = Adder("Adder 1") ##th1.start() ##th2 = Adder("Adder 2") ##th2.start() ##th1.join() ##th2.join() ##print("Result:", num) #### 展示Queue类对象使用的示例 ##from queue import Queue ## ##glist = None ## ##class Producer(Thread): ## def __init__(self, name_, queue, n): ## Thread.__init__(self, name=name_) ## self._queue = queue ## self._num = n ## ## def run(self): # 生产一些数据放入通讯队列 ## for i in range(self._num): ## time.sleep(0.2) ## self._queue.put((self.getName(), i)) ## ##class Consumer(Thread): ## def __init__(self, name_, queue, n): ## Thread.__init__(self, name=name_) ## self._queue = queue ## self._num = n ## ## def run(self): # 从队列中取出数据使用 ## global glist ## list1 = [] ## for i in range(self._num): ## list1.append(self._queue.get()) ## glist = list1 ## ##def main(): ## q = Queue() # 创建一个队列对象作为线程通讯通道 ## p1 = Producer("P1", q, 10) # 建立两个生产线程 ## p2 = Producer("P2", q, 10) ## cons = Consumer("C1", q, 20) # 建立消费线程 ## p1.start() # 启动三个线程 ## p2.start() ## cons.start() ## p1.join() # 等待三个线程完成工作 ## p2.join() ## cons.join() ## print(glist) # 输出全局变量的值 ## ##main() 启动计算