Untitled

mail@pastecode.io avatar
unknown
python
a month ago
1.7 kB
6
Indexable
Never
import multiprocessing
import random
import time
import psutil

def process_C(semaphore):
    try:
        sleep_time = random.random() * 6
        print("Process C sleeping for {:.2f} seconds".format(sleep_time))
        if sleep_time > 4.2:
            raise Exception("Random exception")
        time.sleep(sleep_time)
        print("Process C completed")
    except Exception as e:
        print("Process C failed: {}".format(e))
    finally:
        semaphore.release()


def process_B(semaphore, processes):
    semaphore.acquire()
    p = multiprocessing.Process(target=process_C, args=(semaphore,))
    processes.append(p)
    p.start()
    print(f"Process {p.name} started in process B")
    print("Process B completed")



def process_A(semaphore, processes):
    process_B(semaphore, processes)
    print("Process A completed")


if __name__ == "__main__":
    semaphore = multiprocessing.Semaphore(20)
    processes = []

    while True:
        # Start a new process
        process_A(semaphore, processes)
        # Clean up finished processes
        for p in processes:
            # p.join(timeout=0)
            if not p.is_alive():
                processes.remove(p)
                p.terminate()
                p.join()
                print(f"Process {p.name} removed from list.")
            else:
                try: 
                    cpu_percent = psutil.Process(p.pid).cpu_percent(interval=0.1)
                    if cpu_percent < 0.1:  
                        processes.remove(p)
                        p.terminate()
                        p.join()
                except:
                    pass
        # Sleep a bit to prevent this loop from consuming 100% CPU
        time.sleep(0.1)
Leave a Comment