0

I've just started out with multi threading, so I thought I'd make myself a small and simple example:

import time
import threading

def count(who):
        count = 1
        while count <= 5:
                print who + " counted to: " + str(count)
                time.sleep(0.1)
                count += 1

thread1 = threading.Thread(target=count, args=('i'))
thread1.start()

Which works great and prints out the following:

>>> i counted to: 1
>>> i counted to: 2
>>> i counted to: 3
>>> i counted to: 4
>>> i counted to: 5

The odd thing is however, when I want to change the argument to another like: "john":

thread1 = threading.Thread(target=count, args=('john'))

Hoping it would produce:

>>> john counted to: 1
>>> john counted to: 2
>>> john counted to: 3
>>> john counted to: 4
>>> john counted to: 5

However, it procudes an error:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
TypeError: count() takes exactly 1 argument (4 given)

I'm really not sure what is happening here... Does anyone know?

1 Answer 1

5

Add a comma to make it explicit that you want a tuple:

thread1 = threading.Thread(target=count, args=('john', ))

Currently python thinks the parenthesis are redundant, so ("john") evaluates to "john" which are four characters, hence the message you're getting.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh okay, well I guess that makes sense. Thanks for that explanation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.