zuoye
Posted huweitao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了zuoye相关的知识,希望对你有一定的参考价值。
from threading import Thread from threading import Lock lock = Lock () def pl(): lock.acquire() with open(‘jkl‘,mode= ‘r+‘) as ff: k = ff.read() k = int(k) k += 1 print(‘zhege%s‘%k) pp = str(k) with open(‘jkl‘,mode = ‘r+‘) as ff: ff.write(pp) lock.release() list2 = [] if __name__ == ‘__main__‘: for i in range(20): obj = Thread (target= pl) list2.append(obj) for i in list2: i.start()
1.创建一个文件,文件的第一行写入0,再创建20个任务线程,他们同时打开文件并将文件第一行读出来,加1写回去(将文件原有值覆盖掉)请保证20个任务线程完成后,文件中的第一行一定是20!
from threading import Thread from threading import Lock def issushu(i): for j in range(2,i): if i % j == 0: return False else: return True def worker(aa): while True : try: x = next(aa) except : break else: if issushu(x): print(x) num = iter(range(100,301)) lista = [] for i in range(4): t = Thread (target= worker,args = (num,)) lista.append(t) for t in lista: t.start() for t in lista : t.join()
yield 是生成器关键字,能有效节省系统空间。
def fun(): for i in range(20): x=yield i print(‘good‘,x) if __name__ == ‘__main__‘: a=fun() a.__next__() x=a.send(5) print(x)
以上是关于zuoye的主要内容,如果未能解决你的问题,请参考以下文章