Python multithreading - Call blocking in the background

I recently worked on a program (as you can see from my previous question), and I had problems understanding and implementing multithreading.

I followed the tutorial ( binary streams ) to configure a UDP server that works fine. However, the problem is that when I create a blocking UDP socket in a new stream, the code that I have in my main program, where I originally created the stream, does not work. Here is 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 just want to be able to execute any code in main.py after the startConnection function is called on a new thread (i.e. prints a line in this instance).

I struggled with this program for a long time, Python is new to me, and it seems to me that it is quite difficult. I assume that I should make some mistakes in the way I implemented multithreading, any help would be greatly appreciated!

+4
source share
1 answer

start_new_thread gets a list of functions and arguments, but you directly use the function call: start_new_thread(networkStart.startConnecton()) .

However, I recommend using the threading module ( official documentation) , which has a higher level of abstraction.

 import threading import connections threading.Thread(target=networkStart.startConnecton).start() print 'This should print!' 
+5
source

Source: https://habr.com/ru/post/1469280/


All Articles