fdict= {0: fun1(), 1: fun2()}
# approach 1 : working fine, printing string
print fdict[random.randint(0,1)]
# approach 2 calling
thread.start_new_thread(fdict[random.randint(0,1)],())
#I also tried following approach
fdict= {0: fun1, 1: fun2}
thread.start_new_thread(fdict[random.randint(0,1)](),())
fun1 and fun2 are returning strings. I am able to call these functions using approach 1 but not able to call using approach 2. Getting error as shown below. But approach 1 already proved that these are callable.
thread.start_new_thread(fdict[random.randint(0,1)],())
TypeError : first arg must be callable
The values of fdict
are not functions; they are values returned from func1()
and func2()
respectively.
>>> fdict = {0: fun1, 1: fun2}
>>> thread.start_new_thread(fdict[random.randint(0,1)], ())
thread
is a very low level library where there is no way of joining threads so when your main program finishes before any thread finishes executing its task, you'll be likely to get errors.
You should use threading.Thread
class to prevent these kind of issues from happening:
>>> from threading import Thread
>>> fdict = {0: fun1, 1: fun2}
>>> t = Thread(target=fdict[random.randint(0,1)], args=())
>>> t.deamon = True
>>> t.start()
>>> t.join() # main program will wait for thread to finish its task.
You can see the threading documentation for more information.
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.