Multithreading in python - Blocking call running in background
multithreading, python, udp
Solution
`start_new_thread` receives a function and an arguments list, but you are using directly the function call: `start_new_thread(networkStart.startConnecton())`.
However, I recommend you to use the `threading` module (the official documentation does so), which has a higher level of abstraction.
import threading
import connections
threading.Thread(target=networkStart.startConnecton).start()
print 'This should print!'
Problem
I've been recently working on a program (as you may be able to see from my previous question asked) and I've been having real trouble in understanding and implementing multithreading. I followed a tutorial (binary tides) for setting up a UDP server, which works great. The issue I am having however, is that when I create a blocking UDP socket on a new thread, the code which I have in my main program where I initially created the thread doesn't work. Here is some of my code: main.py: ``` from thread import* import connections start_new_thread(networkStart.startConnecton()) print 'This should print!' ``` networkStart.py: ``` def startConnecton(): userData.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' try: userData.s.bind((HOST, PORT)) except socket.error, msg: print 'Bind failed. Error code: ' +str(msg[0]) + 'Message' +msg[1] sys.exit() print 'Socket bind complete' userData.s.listen(10) # Set the socket to listening mode, if there are more than 10 connections waiting reject the rest print 'Socket now listening' #Function for handling connections. Each new connection is handled on a separate thread start_new_thread(connections.connectionListen()) ``` connections.py: ``` def connectionListen(): while 1: print 'waiting for connection' #wait to accept a connection - blocking call conn, addr = userData.s.accept() userData.clients += 1 print 'Connected with ' + addr[0] + ':' + str(addr[1]) #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments start_new_thread(users.clientthread ,(conn, userData.clients)) ``` I basically just want to be able to execute any code in main.py after the startConnection function is called on a new thread (i.e, print the string in this instance). I've been struggling with this program for quite a while, Python is new to me and I'm finding it quite challenging. I'm assuming I must be making some errors in the way i've implemented multithreading, any help would be much appreciated!