1. 程式人生 > >Python線程同步

Python線程同步

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線程同步