2016-08-03 44 views
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 

誰能幫助爲什麼行爲不同?

+1

' 「{0}」。格式(INT(指數))'是字符串,利用整數'index'代替 – haifzhan

+1

你爲什麼要插入 「{0}」。在多線程版本format'電話嗎?你知道'(thing,)'是一個元組,而'(thing)'只是在分組圓括號中的'thing'嗎? – user2357112

+0

這不是我得到的任何例子的輸出,請發佈與使用的代碼相關的輸出。 –

回答

2

您將索引作爲字符串傳遞給該函數,但您正在檢查與整數的相等性。

另外,做int(index)是多餘的。這已經是一個整數。

您可以通過執行print type(count)

編輯檢查:這裏是你在做什麼的例子。

>>> x = "{0}".format(1) 
>>> x 
'1' 
>>> type(x) 
<class 'str'> 
>>> 1 == x 
False 
+0

謝謝。在使用線程的情況下,我需要將它匹配爲一個字符串。 –

相關問題