注意警告
get_mongo_client()
;如果你想从任何地方打到安全的电话,你需要“标记”
_mongo_client
使用当前进程的PID,如果对象有错误的PID,则丢弃该对象。
_mongo_client = None # Global per process
def get_mongo_client():
# Make sure not to call this within the master process, or things
# will break again.
global _mongo_client
if _mongo_client is None:
_mongo_client = pymongo.MongoClient("mongodb://localhost:27017/")
return _mongo_client
def get_mongo_col(collection, database="testdb"):
client = get_mongo_client()
return client[database][collection]
def func1():
col1 = get_mongo_col("col1")
while True:
col1.insert_one({})
# ...
def func2():
col2 = get_mongo_col("col2")
while True:
col2.insert_one({})
# ...
def main():
# Multiproccesing
p1 = Process(target=func1)
p2 = Process(target=func2)
p1.start()
p2.start()
p1.join()
p2.join()
if __name__ == "__main__":
main()