问题的提出 上一节的例子中,每个线程互相独立,相互之间没有任何关系.现在假设这样一个例子:有一个全局的计数num,每个线程获取这个全局的计数,根据num进行一些处理,然后将num加1.很容易写出这样的代码: # encoding: UTF-8import threadingimport time class MyThread(threading.Thread): def run(self): global num time.sleep(1) num = num+1 msg = self.name…
以多线程为例写个互斥锁 from threading import Thread ,Lockimport timemutex = Lock() n = 100 def task(): global n with mutex: temp = n time.sleep(0.1) n= temp-1 if __name__ == '__main__': t_l = [] start_time = time.time() for i in range(100): t = Thread(target=ta…
一.守护进程 import random import time from multiprocessing import Process def task(): print('name: egon') time.sleep(random.randint(0,3)) print('sex:male') time.sleep(random.randint(0, 3)) print('age:19') if __name__ == '__main__': p=Process(target=task)…