I've got the following code which is based off an example i found here on SO, but when i run it i get an error. Please help, i'm sure its very simple:
def listener(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('',port))
sock.settimeout(1) # n second(s) timeout
try:
while True:
data, addr = sock.recvfrom(1024)
print data
except socket.timeout:
print 'Finished'
def startListenerThread(port):
threading.Thread(target=listener, args=(port)).start()
The error i get is:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner
self.run()
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 477, in run
self.__target(*self.__args, **self.__kwargs)
TypeError: listener() argument after * must be a sequence, not int
A lack of thread safety means that the methods/functions don't have protection against multiple threads interacting with that data at the same time - they don't have locks around data to ensure things are consistent. The async stuff isn't thread safe because it doesn't need to be.
Python is NOT a single-threaded language. Python processes typically use a single thread because of the GIL. Despite the GIL, libraries that perform computationally heavy tasks like numpy, scipy and pytorch utilise C-based implementations under the hood, allowing the use of multiple cores.
For catching and handling a thread's exception in the caller thread we use a variable that stores the raised exception (if any) in the called thread, and when the called thread is joined, the join function checks whether the value of exc is None, if it is then no exception is generated, otherwise, the generated ...
Python doesn't support multi-threading because Python on the Cpython interpreter does not support true multi-core execution via multithreading. However, Python does have a threading library.
The error is coming from the following line:
threading.Thread(target=listener, args=(port)).start()
The args
parameter needs to be a sequence, I think your intention is to use a tuple, but wrapping a single value in parentheses does not accomplish this. Here is what you need to change it to:
threading.Thread(target=listener, args=(port,)).start()
Here is a simple example showing the difference:
>>> (100) # this is just value 100
100
>>> (100,) # this is a tuple containing the value 100
(100,)
In the last line, args=(port)
is equivalent to args=port
. You need to put port
into a proper tuple like this: args=(port,)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With