import os
import sys
from random import choice
from time import time, sleep
from multiprocessing import Manager
from concurrent.futures import ProcessPoolExecutor, as_completed


def writer(LCK, file_name, cycles, itr):
    _t = time()
    num = choice(range(100_000))
    ospid = os.getpid()
    for _i in range(cycles):
        try:
            # with LCK: # With Lock takes more time, without Lock it worked for 116 parallel processes
            with open(file_name, 'a') as lfile:
                sleep(0.36)
                dat = [f'{num}({_i}) generated by {ospid} registered as {itr}', '\n']
                lfile.writelines(dat)
                sleep(0.36)
        except Exception as err:
            return err

    return f'{ospid} Succeeded. Time elapsed: {round(time() - _t, 1)}'


def aio_writer(file_name, workers, cyc):
    manager = Manager()
    L = manager.Lock()
    with ProcessPoolExecutor(max_workers=workers) as executor:
        pool_ = {
            executor.submit(
                writer,
                L,
                file_name,
                cyc,
                d
            ): d for d in range(workers)
        }
    for future in as_completed(pool_):
        print(future.result())


if __name__ == '__main__':
    fname = 'misd.TXT'
    cyc = 100
    aio_writer(fname, 116, cyc)
