程序应该响应并在时间变量指定的时间内打印val。
import timeit
from threading import Thread
val = 0
time = 3.05274241722e-05
def function1():
global val
for i in range(0,10000):
val = val+i
return val
def function2():
global val
for i in range(0,10000):
val = val+i
return val
if __name__ == '__main__':
start_time = timeit.default_timer()
Thread(target = function1).start()
Thread(target = function2).start()
while time-1 <=(timeit.default_timer() - start_time):
if time-1 >(timeit.default_timer() - start_time):
break
print time-1
print timeit.default_timer() - start_time
print val
pass
print val
Thread(target = function1).exit()
Thread(target = function2).exit()
还请让我知道我是否正确使用了线程。谢谢
答案 0 :(得分:0)
您的time-1
是一个负值,它总是小于(timeit.default_timer() - start_time)
,因此它是一个无限循环,if
语句更加冗余。另外,你使用线程的方式是错误的。
尝试以下代码
import timeit
from threading import Thread
val = 0
time = 2.38282775879e-05
flag = False
def function1():
global val
global flag
for i in range(0,1000):
if not flag:
val = val+i
print val
else:
break
def function2():
global val
global flag
for i in range(0,1000):
if not flag:
val = val+i
print val
else:
break
if __name__ == '__main__':
f1 = Thread(target = function1)
f2 = Thread(target = function2)
start_time = timeit.default_timer()
f1.start()
f2.start()
f1.join(time)
f2.join(time)
flag = True
end_time = timeit.default_timer()
f1.join()
f2.join()
if time <= end_time - start_time:
print "Timeout"
else:
print "Finished before timeout"
print end_time - start_time
print val