Created
August 13, 2018 15:28
-
-
Save aydinemre/f7788ca3bafaaac77fd5d8cd95f9212a to your computer and use it in GitHub Desktop.
Python Multiprocess shared variable example
This file contains 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
import multiprocessing | |
from functools import partial | |
# Manager to create shared object. | |
manager = multiprocessing.Manager() | |
# Create a global variable. | |
dictionary = manager.dict() | |
# Each process will run this function. | |
def fetch(lock, item): | |
# Do cool stuff | |
lock.acquire() | |
dictionary[item] = 0 | |
# Write to stdout or logfile, etc. | |
lock.release() | |
if __name__ == '__main__': | |
# Each item will map to function. | |
my_list = range(5) | |
# Create a lock. | |
l = manager.Lock() | |
# Multiprocess pool. | |
pool = multiprocessing.Pool(processes=4) | |
func = partial(fetch, l) | |
# Map each item to function | |
pool.map(func, my_list) | |
# Close pool. | |
pool.close() | |
# Wait for all thread. | |
pool.join() | |
# Print meta_info | |
print(dictionary) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment