0
我想寫一個簡單的函數,並從一個線程調用不同的值。正常調用時,該功能完美運行。但只要我們從線程調用它,函數內的條件語句就不起作用。Python:線程爲什麼條件語句的工作方式不同?
def func(count):
print "In func count = {0}".format(count)
if count == 3:
print "If count = {0}".format(count)
print "Sleeping as count = {0}".format(count)
else:
print "Else count = {0}".format(count)
print "{0} so No sleep".format(count)
--------------------------------------------------
雖然調用上述函數可以很好地工作。
print func(2)
print func(3)
print func(4)
輸出是:
In func: count = 2
Printing Else Count = 2
In func: count = 3
Printing If Count = 3
In func: count = 4
Printing Else Count = 4
------------------------------
不過,雖然在一個線程中使用相同的功能的行爲是不同的。
thread_arr = []
for index in range(2,5,1):
thread_arr.append(threading.Thread(target=func, args=("{0}".format(int(index)))))
thread_arr[-1].start()
for thread in thread_arr:
thread.join()
輸出是:
In func: count = 2
Printing Else Count = 2
In func: count = 3
Printing Else Count = 3
In func: count = 4
Printing Else Count = 4
誰能幫助爲什麼行爲不同?
' 「{0}」。格式(INT(指數))'是字符串,利用整數'index'代替 – haifzhan
你爲什麼要插入 「{0}」。在多線程版本format'電話嗎?你知道'(thing,)'是一個元組,而'(thing)'只是在分組圓括號中的'thing'嗎? – user2357112
這不是我得到的任何例子的輸出,請發佈與使用的代碼相關的輸出。 –