Threading, Timing, or function use?

I had a problem formulating an idea on how to work with this problem. Please help.

My project consists of an N x N grid with a series of blocks that must move in a random direction and at a random speed within this grid (every 0.1 seconds, the location of the block is updated with speed). I have three โ€œspecialโ€ blocks that are expected to have separate motion functions. I will have other blocks (many of them) doing nothing but updating their location, and make sure they stay in the grid.

Now these three blocks have functions that go beyond the limits of movement, but each of them starts individually, waiting for the completion of the special function of the other block (block 2 will wait on block 1, block 3 will wait for 2 and return it to block 1, etc. .) This queue will start while driving. I want the movement to never stop. After the blocking function of each block is executed n times, the code ends.

My question is this: should I use threads to start and stop functions without movement, or is there a way to just set the time and set logical values โ€‹โ€‹that could use the class function after 0.1 seconds to continuously move objects (and, obviously, the loop again and again), and then use the counts to complete the program together? If so, how would you write the main function for this in Python? For everyone this happens, does anyone think that Java will be much faster than Python in this, especially if you write data to a .txt file?

+4
source share
2 answers

It is best, perhaps, to process everything at once in one update operation, rather than trying to use Threads. This is primarily due to the fact that Global Interpreter Lock will prevent the simultaneous processing of multiple threads. What you after looks something like this:

def tick(): for box in randomBoxes: box.relocate() specialBlock1.relocate() specialBlock2.relocate() specialBlock3.relocate() 

Then we define the second function, which will endlessly run our first function:

 def worker(): while True: tick() sleep(0.1) 

Now that we have an interval or sort, we will run Thread, which runs in the background and processes our updates on the screen.

 from threading import Thread t = Thread(target = worker, name = "Grid Worker") t.daemon = True # Useful when this thread is not the main thread. t.start() 

In our tick() function, we worked on the fact that specialBlocks 1, 2, and 3 work in the established order. The remaining fields accept their actions regardless of what others do.

+2
source

If you put calls to special functions together in one function, you get coordination ( 2 ).

 def run(n, blocks): for i in range(n): for b in blocks: b.special() 

As for the speed of Python and Java, it depends on many things, such as the exact implementation. Too little information to say.

0
source

All Articles