Skip to content

Instantly share code, notes, and snippets.

Created May 16, 2016 06:43
Show Gist options
  • Save anonymous/36726976a550bc80926464060c0186ac to your computer and use it in GitHub Desktop.
Save anonymous/36726976a550bc80926464060c0186ac to your computer and use it in GitHub Desktop.
queue_howto
# from multiprocessing import Process
# import os
#
#
# def info(title):
# print(title)
# print('module name:', __name__)
# print('parent process:', os.getppid())
# print('process id:', os.getpid())
#
#
# def f(name):
# info('function f')
# print('hello', name)
#
#
# if __name__ == '__main__':
# info('main line')
# p = Process(target=f, args=('bob',))
# p.start()
# p.join()
import queue, threading, os, time
def do_work(item):
print(os.getppid(), os.getpid(), threading.get_ident(), threading.current_thread().name, 'doing work: ', item)
def worker():
while True:
item = q.get()
if item is None:
break
time.sleep(item)
do_work(item)
q.task_done()
num_worker_threads = 2
q = queue.Queue()
threads = []
for i in range(num_worker_threads):
t = threading.Thread(target=worker, name='Thread_' + str(i))
t.start()
threads.append(t)
source = [1, 1, 1, 1, 1]
for item in source:
q.put(item)
# block until all tasks are done
# q.join()
#
# # stop workers
# for i in range(num_worker_threads):
# q.put(None)
# for t in threads:
# t.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment