I'm currently in the process of writing a client server app as an exercise and I've gotten pretty much everything to work so far, but there is a mental hurdle that I haven't been able to successfully google myself over.
In the server application am I correct in my thinking that threading the packet handler and database handler to work from a stack is the right thing to do? The idea is that one thread loops listening for packets and adds the data to a stack and then the other thread pops the data off the bottom of the stack and does some checks against an SQL db.
In this particular case, it's more important for the packet handler to keep working. I guess my question is, is this an appropriate use of threads and where am I going to run into problems that require thread locking, for example, should I lock the db handler when the packet thread adds to the stack to avoid an issue with trying to write and read say, the only value in the stack, etc.
Thanks everyone!
Here is a snippet of the code, mind you it's in progress so don't judge, also my first attempt at python (which I am enjoying more than perl or php at the moment!).
class socketListen(threading.Thread):
def run(self):
while True:
datagram = s.recv('1024')
if not datagram:
break
packetArray = datagram.split(',')
if packetArray[0] = '31337':
listHandle.put(packetArray)
s.close()
class stackOperations(threading.Thread):
def run(self):
while True:
#pull the last item off the stack and run ops on it
#listHandle.getLast is the last item on the queue
def
class listHandle():
def put(shiftData):
if not mainStack:
mainStack = []
mainStack.insert(0,shiftData)
def getLast:
return mainStack.pop()
This is what queues are for. Replace stack with queue and no, you won't have to use any other synchronization methods. Incidentally, multiprocessing is better than threading, since it can take advantage of multicore/hyperthreaded processors. The interfaces are pretty similar, so it's worth looking into switching.
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