如何在python中停止或等待新创建的进程访问函数,而当前进程正在访问同一函数

2ic8powd  于 2023-03-20  发布在  Python
关注(0)|答案(1)|浏览(172)
import multiprocessing as mp
import threading

processingP = mp.Process(target=a_process, args=(processCollection,mongoIP, mongoPort))
processingP.start()

def createSigneIndexForCollection(mongoDatabase, collectionName, columnName):
    rawlogCollection = mongoDatabase[collectionName]
    rawlogCollection.create_index([(columnName , 1)])

def createIndexForCollection(mongoDatabase, collectionName):
    columnsToBeIndexed = ["Name", "Message",etc.]
    for columnName in columnsToBeIndexed:
        indexThread = threading.Thread(target=createSigneIndexForCollection, args=(mongoDatabase, collectionName, columnName))
        indexThread.start()
        indexThread.join()

def a_process(processCollection, mongoIP, mongoPort):
    
    mongoDatabase = getDatabase(mongoIP, mongoPort, mongoDatabase)
    
    createIndexForCollection(mongoDatabase, processCollection)
     
    if processCollection != "NULL":
        ScanningThread = threading.Thread(target=check, args=(mongoDatabase, processCollection))
        ScanningThread .start()
        ScanningThread .join()

在上面的代码片段中,每个进程将每隔6分钟启动一次。每个进程将访问createIndexForCollection函数并转到下一行。但我不希望新创建的进程在当前进程访问createIndexForCollection函数时访问该函数。一旦当前进程在createIndexForCollection函数上执行完毕,则只有下一个进程才应访问创建用于集合的索引函数

raogr8fs

raogr8fs1#

您可以使用跨进程共享的令牌和条件变量来序列化进程,如下所示:

import time
import multiprocessing as mp

def worker(index: int, token, cv):
    with cv:
        if index > 0 and index != token.value:
            cv.wait_for(lambda : index == token.value)
        print(f'worker {index}, token: {token.value}')
        token.value += 1
        cv.notify_all()

def main():
    cv = mp.Condition()
    token = mp.Value('i', 0, lock=False)
    procs = []
    for idx in range(10):
        p = mp.Process(target=worker, args=(idx, token, cv))
        p.start()
        procs.append(p)
        # time.sleep(0.01)

    for p in procs:
        p.join()

if __name__ == '__main__':
    main()

结果:

$ python3 b.py                   
worker 0, token: 0
worker 1, token: 1
worker 2, token: 2
worker 3, token: 3
worker 4, token: 4
worker 5, token: 5
worker 6, token: 6
worker 7, token: 7
worker 8, token: 8
worker 9, token: 9

祝你好运!

相关问题