In python, there is no true concurrency, except through the multiprocessing module, since the GIL is then not part of the image.
, , , . , Pypubsub , , ( pubsub , , :) , mp, concurrency , ?
, , , , , , , . , "" : , , . , . .
3 , :
from multiprocessing import Process, Queue, Lock
from Queue import Empty as QueueEmpty
from random import randint
def log(lock, threadId, msg):
lock.acquire()
print 'Thread', threadId, ':', msg
lock.release()
def auxThread(id, lock, sendQueue, recvQueue, genType):
log(lock, id, 'starting')
while True:
if randint(1,10) > 7:
event = dict(type = genType, fromId = id, val = randint(1, 10) )
log(lock, id, 'putting message type "%(type)s" = %(val)s' % event)
sendQueue.put(event)
maxWait = 1
try:
msg = recvQueue.get(False, maxWait)
log(lock, id, 'got message type "%(type)s" = %(val)s from thread %(fromId)s' % msg)
if (msg['val'] == 'DONE'):
break
except QueueEmpty:
pass
log(lock, id, 'done')
def createThread(id, lock, postOffice, genType):
messagesForAux = Queue()
args = (id, lock, postOffice, messagesForAux, genType)
auxProc = Process(target=auxThread, args=args)
auxProc.daemon = True
return dict(q=messagesForAux, p=auxProc, id=id)
def mainThread():
postOffice = Queue()
lock = Lock()
msgThreads = [
createThread(1, lock, postOffice, 'heartbeat'),
createThread(2, lock, postOffice, 'new_socket'),
createThread(3, lock, postOffice, 'keypress'),
]
dispatch = dict(
heartbeat = (2,),
keypress = (1,),
new_socket = (3,),
)
for th in msgThreads:
th['p'].start()
count = 0
while True:
try:
maxWait = 1
msg = postOffice.get(False, maxWait)
for threadId in dispatch[msg['type']]:
thObj = msgThreads[threadId - 1]
thObj['q'].put(msg)
count += 1
if count > 20:
break
except QueueEmpty:
pass
log(lock, 0, "Main thread sending exit signal to aux threads")
for th in msgThreads:
th['q'].put(dict(type='command', val='DONE', fromId=0))
for th in msgThreads:
th['p'].join()
log(lock, th['id'], 'joined main')
log(lock, 0, "DONE")
if __name__ == '__main__':
mainThread()
, pypubsub, pypubsub, , - , pypubsub . , mp ( ), pypubsub / , .