Let’s say I’m building a big game, and some process needs to happen over a whole lot of frames, this could be anything from downloading map files from some server, to running complex simulations and then using the BGE as a visualizer.
Either way, the traditional module mode won’t quite cut it.
So we need some way of doing … multiprocessing.
I was having trouble finding examples in the BGE, but with the help of this link I came up with this demo.
***What it does:
Sends some data from the BGE to a frame-rate-independent script, which sends some information back.
To prove independence from frame-rate, the thread will wait half a second (using time.sleep(0.5)) before replying to the BGE. This also serves to show that when using multiple threads, execution order/finishing times aren’t guaranteed
How it does it:
The python multiprocessing module, and some input/output Queues, see the above link for details
Additional notes:
- Since the thread is independent from the BGE, it can continue running after the BGE has closed. As a result, I’ve dumped a check to kill the thread within a few seconds of the BGE closing. There are probably better ways to do this.
- Do not import bge from the frame-independent script, data corruption is possible/likely
- The thread will restart if it quits and blender is still running
***Expected Output:
With this demo file, when you hit play, the console will display that the thread has started. if you hit spacebar once, you’ll see:
Blender Game Engine StartedStarting Thread
Thread Started
BGE Sending: "Test #1"
THREAD Recieved: "Test #1"
THREAD Sending: "Reply To Test #1"
BGE Recieved: "Reply To Test #1"
Blender Game Engine Finished
Thread Quit
There is a half-second break between the thread sending and receiving, so it is easy to get things like:
Blender Game Engine Started
Starting Thread
Thread Started
BGE Sending: "Test #1"
THREAD Recieved: "Test #1"
THREAD Sending: "Reply To Test #1"
BGE Recieved: "Reply To Test #1"
BGE Sending: "Test #2"
THREAD Recieved: "Test #2"
BGE Sending: "Test #3"
THREAD Sending: "Reply To Test #2"
THREAD Recieved: "Test #3"
BGE Recieved: "Reply To Test #2"
THREAD Sending: "Reply To Test #3"
BGE Recieved: "Reply To Test #3"
Blender Game Engine Finished
Thread Quit
***Download:
Thread test 2.blend (492 KB)
Final Words:
Why did the multithread chicken cross the road?other To side to the get
It’s multithreaded, which inherently creates … problems!