orange_watch orange_watch - 4 months ago 7
Python Question

Python : While threading why does the conditional statement work differently?

I was trying to write a simple function and call it from a thread for different values. The function worked perfectly when called normally. But as soon as we call it from a thread the conditional statements inside the function do not work.

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)
--------------------------------------------------


While calling the above function works perfectly.

print func(2)
print func(3)
print func(4)


Output is :

In func: count = 2
Printing Else Count = 2

In func: count = 3
Printing If Count = 3

In func: count = 4
Printing Else Count = 4


------------------------------


But while using the same function in a thread the behavior is different.

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()


Output is :

In func: count = 2
Printing Else Count = 2
In func: count = 3
Printing Else Count = 3
In func: count = 4
Printing Else Count = 4


Can anyone help why is the behavior different?

Answer

You passed the index as a string to the function, but you are checking for equality with an integer.

Also, doing int(index) is redundant. It's already an int.

You can check this by doing print type(count)

Edit: Here's an example of what you're doing.

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