Python线程同步

发布时间:2019-08-31 09:46:27编辑:auto阅读(1693)

    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_反射