码迷,mamicode.com
首页 > 编程语言 > 详细

Python线程同步

时间:2018-04-12 16:42:57      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:Python线程同步

from random import randint import threading from time import ctime, sleep data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] class MyThread(threading.Thread):     lock = threading.Lock()     def __init__(self, task):         super(MyThread, self).__init__()         self.task = task     def run(self):         print("In time:{} Start Function:{} ".format(ctime(), self.task.__name__))         self.lock.acquire()         self.task()         self.lock.release() def a():     #从后往前依次修改列表中的元素,     for i in data[::-1]:         new_val = 'xxx%s' % (randint(100, 150))         index = data.index(i)         data[index] = new_val         print("Original value:{} with index:{} modified to:{}".format(i, index, new_val)) def b():     #从前往后依次读取列表     for i in data:         print("Read Value:{} index:{}".format(i, data.index(i))) def main():     funcs = [a, b]     threads = []     loop = range(len(funcs))     for i in loop:         t = MyThread(funcs[i])         threads.append(t)     for i in loop:         threads[i].start()     for i in loop:         threads[i].join() if __name__ == '__main__':     main()     print(" all DONE!!!")


Python线程同步

标签:Python线程同步

原文地址:http://blog.51cto.com/freshair/2097477

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!