Reputation: 10159
New to Python multi-thread and write such simple program, here is my code and error message, any ideas what is wrong? Thanks.
Using Python 2.7.
import time
import thread
def uploader(threadName):
while True:
time.sleep(5)
print threadName
if __name__ == "__main__":
numOfThreads = 5
try:
i = 0
while i < numOfThreads:
thread.start_new_thread(uploader, ('thread'+str(i)))
i += 1
print 'press any key to exit test'
n=raw_input()
except:
print "Error: unable to start thread"
Unhandled exception in thread started by <pydev_monkey._NewThreadStartupWithTrace instance at 0x10e12c830>
Traceback (most recent call last):
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydev_monkey.py", line 521, in __call__
return self.original_func(*self.args, **self.kwargs)
TypeError: uploader() takes exactly 1 argument (7 given)
thanks in advance, Lin
Upvotes: 2
Views: 165
Reputation: 640
In the following, threadName is now a global variable defined towards the top of the program code, then the variable is initialized before the new thread is started with the target being the upload function.
Try this:
import time
import thread
threadName = ''
def uploader():
while True:
time.sleep(5)
print threadName
if __name__ == "__main__":
numOfThreads = 5
try:
i = 0
while i < numOfThreads:
threadName = 'thread' + str(i)
newThread = threading.Thread(target=uploader)
newThread.start()
i += 1
print 'press any key to exit test'
n=raw_input()
except:
print "Error: unable to start thread"
Upvotes: 1
Reputation: 11601
The args of thread.start_new_thread
need to be a tuple. Instead of this:
('thread' + str(i)) # results in a string
Try this for the args:
('thread' + str(i),) # a tuple with a single element
Incidentally, you should check out the threading
module, which is a higher-level interface than thread
.
Upvotes: 3