Search code examples
pythonmultithreadingmultiprocessingprobability

I'm trying to calculate a probability of a function returning True by while(True) looping it in Python but I can't get it to work


I'm trying to calculate the probability of a predefined function that símulates an arbitrary event. Is there maybe a library that does this or a better way?

from multiprocessing import cpu_count
import multiprocessing

def play_event():
    "predefined function which either returns True or False"

def process(total_events, favorable_results, lock):
    while(True):
        event = play_event()
        with lock:
            total_events += 1
            if(event == True):
                favorable_results += 1
        

if __name__ == "__main__":
    seed(1)

    manager = multiprocessing.Manager()
    lock = manager.Lock()
    number_processes = cpu_count()

    total_events = manager.Value(int, 0)
    favorable_results = manager.Value(int, 0)

    jobs = []

    for i in range(number_processes):
        p = multiprocessing.Process(target=process, args=(total_events, favorable_results, lock))
        jobs.append(p)
        p.start()

    while(True):
        if(total_events.value > 0):
            print(Decimal(favorable_results.value)/total_events.value)

Right now I'm getting the error: TypeError: unsupported operand type(s) for +=: 'ValueProxy' and 'int', in the process function when i add 1 to the total_events. Unfortunately, I don't think this is the only error. Before I didn't get this error and total_events.value was constantly 1.


Solution

  • Use total_events.get() to get the current value, and total_events.set(x) to set the value to x. - John Gordon

    His answer is in the reply to my question.