-
-
Save zhanglongqi/4b5ef3bd9f8688ea2af9cf1580d262f5 to your computer and use it in GitHub Desktop.
queue_howto
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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