bge Python AddObject and multithreading

Hi, i’m trying with python in bge, to add a lot of cubes with a for loop, so i discovered a way to avoid blender’s freezes. I found the threading module, which allows to run a for loop and blender together. Perfect! First of all this is my code:

import bge
import threading

cont = bge.logic.getCurrentController()
own = cont.owner
scene = bge.logic.getCurrentScene()

def gen():
    for i in range(30):
        for j in range(30):
            add = scene.addObject("Cube", own, 0)
            add.position.x = i
            add.position.y = j


if i run only the for loops works, but with threading the console give me this error:

Exception in thread Thread-1:Traceback (most recent call last):
File “C:\Program Files\Blender Foundation\Blender\2.77\python\lib”, line 914, in _bootstrap_inner
File “C:\Program Files\Blender Foundation\Blender\2.77\python\lib”, line 862, in run
self._target(*self._args, **self._kwargs)
File “”, line 11, in gen
SystemError: Blender Game Engine data has been freed, cannot use this python variable

Can anyone help me please?

i have read that threading need more steps then just start it. like this page or this #edit removed link had nothing to do with bge (bpy based)

import threading

def to_run(): # should not take arguments.
    ... # code to execute in the thread (can be a loop, ...) 
        # it uses the same variables as in the main thread.

new_thread = threading.Thread() # create a new thread object. = to_run
new_thread.start() # the new thread is created and then is running.

also some advice, depends on what you are doing, but include the cont,own,scene in the function, not outside it.

As far as I know, editing bge specific things (scene, objects etc) in threads is not safe.
Bge is not designed to work with threads.
So this approach won’t work. Try something else :(.

BGE is not thread safe. Have a look at this set of slides for how to do multithreading and it’s caveats in python: