Python 线程同步 本文共有3645个字,关键词: 使用Thread对象的Lock和RLock可以实现简单的线程同步,这两个对象都有acquire方法和release方法。对于每次只允许一个线程操作的数据,可以将操作放到acquire和release方法之间。多线程的优势在于可以同时运行多个任务,但当线程需要共享数据时,可能存在数据不同步的问题。 示例一 import threading from time import sleep from datetime import datetime class MyThread(threading.Thread): def __init__(self, func, args, name=''): threading.Thread.__init__(self) self.name = name self.func = func self.args = args def getResult(self): return self.res def run(self): #调用类内的方法 print('*********MyThread Run Start**********') print('param:---->' + self.name) #完成之后可以调用传入的方法 threadLock.acquire() print_time(self.name,2,3) threadLock.release() self.res = self.func(*self.args) print('*********MyThread Run End**********') def print_time(threadName, delay, counter): while counter: sleep(delay) print(f'{threadName}:{get_date_str(datetime.now())}') counter -= 1 def get_date_str(dt): return datetime.strftime(dt, '%Y-%m-%d %H-%M-%S') def subthread(thid, sec): print(f'subthread-线程{thid},Start at {get_date_str(datetime.now())} ,sleep{sec} s') sleep(sec) print(f'subthread-线程{thid},End at {get_date_str(datetime.now())} ,sleep{sec} s') def main(): print('-' * 10 + 'ALL START:' + get_date_str(datetime.now()) + '-' * 10) threads.append(MyThread(subthread, (1, 2), subthread.__name__ + '线程一')) threads.append(MyThread(subthread, (2, 3), subthread.__name__+ '线程二')) for i in range(len(threads)): threads[i].start() for i in threads: i.join() # 线程全部结束之后主线程才会退出 print('-' * 10 + 'ALL End:' + get_date_str(datetime.now()) + '-' * 10) if __name__ == '__main__': threadLock = threading.Lock() threads = [] main() 示例二 import threading from time import sleep from datetime import datetime class MyThread(threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.name = name self.threadID = threadID self.counter = counter def run(self): # 调用类内的方法 print('*********MyThread Start**********') print('param:---->' + self.name) # 完成之后可以调用传入的方法 threadLock.acquire() print_time(self.name,self.counter,3) threadLock.release() print('*********MyThread End**********') def get_date_str(dt): return datetime.strftime(dt, '%Y-%m-%d %H-%M-%S') def print_time(threadName, delay, counter): while counter: sleep(delay) print(f'{threadName}:{get_date_str(datetime.now())}') counter -= 1 def main(): print('-' * 10 + 'ALL START:' + get_date_str(datetime.now()) + '-' * 10) threads.append(MyThread(1, 'thread-1', 1)) threads.append(MyThread(2, 'thread-2', 2)) for i in range(len(threads)): threads[i].start() for i in threads: i.join() # 线程全部结束之后主线程才会退出 print('-' * 10 + 'ALL End:' + get_date_str(datetime.now()) + '-' * 10) if __name__ == '__main__': threadLock = threading.Lock() threads = [] main() 「一键投喂 软糖/蛋糕/布丁/牛奶/冰阔乐!」 赞赏 × 梦白沙 (๑>ڡ<)☆谢谢老板~ 1元 2元 5元 10元 50元 任意金额 2元 使用微信扫描二维码完成支付 版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。 Python 2022-04-23 评论 285 次浏览