我有以下代码,这是我编写的模拟程序的精简版本:
import sched, time
import _thread as thread, threading
lock = threading.Lock()
f0=open("f0.out",'w',1)
f1=open("f1.out",'w',1)
f2=open("f2.out",'w',1)
# f3=open("f3.out",'w',1)
# f4=open("f4.out",'w',1)
# files = [f1,f2,f3,f4]
files = [f1,f2,]
def demoWrite(destFile):
destFile.write("Hello\n")
def createSchedule(outFile):
s = sched.scheduler(time.time, time.sleep)
for i in range(1,100):
s.enter(1,1,demoWrite,(outFile,))
s.run()
with lock:
print('Thread Done',outFile)
createSchedule(f0)
f0.close()
for f in files:
thread.start_new_thread ( createSchedule, (f,) )
for f in files:
print(f)
f.close()
print('Done')
我遇到的问题是它会创建文件,但不会写入文件,也不会打印Thread Done
输出。
对于f0,但是没有线程,它可以毫无障碍地工作。
我在完整的程序中得到了同样的行为。
答案 0 :(得分:3)
工作代码:
import sched, time
import threading
lock = threading.Lock()
f0=open("f0.out",'w',1)
f1=open("f1.out",'w',1)
f2=open("f2.out",'w',1)
# f3=open("f3.out",'w',1)
# f4=open("f4.out",'w',1)
# files = [f1,f2,f3,f4]
files = [f1,f2,]
def demoWrite(destFile):
destFile.write("Hello\n")
def createSchedule(outFile):
s = sched.scheduler(time.time, time.sleep)
for i in range(1,100):
s.enter(1,1,demoWrite,(outFile,))
s.run()
with lock:
print('Thread Done',outFile)
outFile.close()
createSchedule(f0)
f0.close()
for f in files:
t = threading.Thread(target=createSchedule, args=(f,))
t.start()
# thread.start_new_thread ( )
print('Done')
我做了什么:
t = threading.Thread(target=createSchedule, args=(f,)); t.start()