H
H
Held69912021-11-09 20:07:13
Python
Held6991, 2021-11-09 20:07:13

How to fix a bug in process simulation?

Hello, I'm trying to implement a process simulation from this topic - https://qna.habr.com/q/1072594
It came out, here is a code in which the asynchrony is slightly non-asynchronous, because I need the processes inside to mainrun constantly for 15 seconds, and not wait until everything is done, but only then do the next iteration. Please tell me how to fix it so that it works exactly as it was intended. Many thanks in advance to everyone.

import random
import asyncio
from time import time


async def CreateQueue():
    print(first_queue)
    if len(first_queue) < 6:
        for i in range(6 - len(first_queue)):
            t = random.uniform(1, 2)
            await asyncio.sleep(t)
            first_queue.append(t)
    else:
        await asyncio.sleep(random.uniform(1, 2))
        items_status[0] += 1


async def QueueWorking():
    while True:
        try:
            item = first_queue.pop(0)
            break
        except:
            pass
    if p1.IsBusy == 0:
        t2 = asyncio.create_task(WorkingWithProcess(item, p1))
        await t2
    elif p2.IsBusy == 0:
        t3 = asyncio.create_task(WorkingWithProcess(item, p2))
        await t3
    else:
        pass


class FirstProcess():
    Name = 'first'
    IsBusy = 0
    Delay = 5
    Item = []


class SecondProcess():
    Name = 'second'
    IsBusy = 0
    Delay = 5
    Item = []


async def WorkingWithProcess(item, p):
    p.Item.append(item)
    await asyncio.sleep(p.Delay)
    print(p.Item, 'finished by', p.Name, 'process')
    p.Item.pop()
    items_status[1] += 1


async def main():
    # a = int(input("Time: "))
    process_time = time()
    a = 15
    while time() - process_time < a:
        t1 = asyncio.create_task(CreateQueue())
        await t1
        t4 = asyncio.create_task(QueueWorking())
        await t4
        print(time() - process_time)
    print(first_queue,items_status)

items_status = [0, 0]
first_queue = []
p1 = FirstProcess()
p2 = SecondProcess()
asyncio.run(main())

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question