Search Unity

Question Executing instructions in parallel

Discussion in 'Scripting' started by OnlyCORE, Nov 28, 2022.

  1. OnlyCORE

    OnlyCORE

    Joined:
    Mar 29, 2022
    Posts:
    4
    Hey, I have model of a factory which consists of 4 machines and I'm basically making a digital twin.
    My controller script reads a set of instructions from a text file.
    The instructions look for example like this:

    command Object name value
    move Piston_1 20
    waitfor Piston_1_Sensor true
    wait 5 (waits 5 seconds)

    I have been using coroutines which were perfect for solving waiting for sensors or seconds in real time
    yield return new WaitUntil(() => Piston_1_Sensor);

    and the next instruction would start only after the sensor changed to true.
    or
    yield return new WaitForSecondsRealtime(5)


    The trouble is when I wanted to execute multiple instructions at the same time. I read the coroutines don't really support that.

    So I need to read from 4 different files with instructions (one for each machine) and execute them at the same time with the ability to use the WaitUntil and WaitForSecondsRealtime.
    Any ideas? Thanks!
     
  2. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    4,000
    You can start as many coroutines as you like. Each coroutine runs seperate from each other.
     
  3. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,111
    What you describe shows that you're mixing up several independent concepts.
    Namely multi-threading (physical parallelism) and parallel simulation.

    If you make a game that's merely simulating some factory process, for example, you don't actually need to run the code in parallel. Computers are fast enough to process things by time-sharing, also called multi-tasking, and this is how we could have multi-tasking operating systems before multi-core CPUs were actually available, which would allow many interleaved applications running at the same time. They were never truly running in parallel, but you wouldn't really notice until you'd really burden the system, then everything would simply slow down.

    So why not borrow the lessons from how we managed to achieve this in real life?

    Each process needs an isolated environment, to allow them to not cross-contaminate each other states, and a task manager, which makes sure that processes are run in short intervals until their tasks are done.

    And coroutines already, kind of, do this by design.
     
    Bunny83 likes this.
  4. OnlyCORE

    OnlyCORE

    Joined:
    Mar 29, 2022
    Posts:
    4
    Oh wow, I just assumed it didn't...
    I implemented it, squashed some bugs and it's working great! Thanks mate ;)