1.创建一个文件,文件的第一行写入0,再创建20个任务线程,他们同时打开文件并将文件第一行读出来,加1写回去(将文件原有值覆盖掉)请保证20个任务线程完成后,文件中的第一行一定是20!
from threading import Thread with open('test', mode='w') as f: f.write('0') def cre_thr(): with open('test', mode='r') as e: a = int(e.read()) print(a) a += 1 with open('test', mode='w+') as g: g.write(str(a)) print(g.read()) if __name__ == '__main__': for i in range(20): thr = Thread(target=cre_thr) thr.start() thr.join()