I just don't know how to share the window object and the sprites between two threads. Man, I don't even know how to share an object between two functions. Should I use global / static or keep passing the object by reference somehow?
Global variables need to be used sparingly, and I would recommend to avoid them because they can be misused easily in Python:
global_var = 0
class Thread(threading.Thread):
def run(self):
global_var = 1
This code doesn't modify the global object, it creates local object named global_var. You need to write “global global_var” to let Python know you want to use a global variable.
If you pass a reference to the thread, you need to be careful too, because some basic types are immutable. If you pass a bool to a function, the function can't modify the bool object itself (the one referenced from the caller), so all it can do is create a new bool object and store it in a local reference.
If you just create a class containing the thread data, you won't have these problems:
import threading
class ThreadData(object):
def __init__(self, window):
self.window = window
class Thread(threading.Thread):
def __init__(self, data):
threading.Thread.__init__(self)
self.data = data
def run(self):
for event in self.window.iter_events():
pass
In your thread's loop, you can use a clock to retrieve the elapsed time since the last loop iteration, decide if you need to go idle, and if so call time.sleep().
I'm not familiar with multithreading with SFML, but I don't remember reading that you need to be especially careful about the window object when handling its events in one thread and displaying stuff on it in another thread. But maybe I've just missed/forgotten some information.
Now, the thing with Python is, only one thread will run at once. What I can do in the binding is allow another thread to run while waiting for a function to finish, like window.display(). But I haven't done this kind of optimization yet because I'd like to have some real world example of the performance benefit it gives.
An easy to have true parallelism is to use processes instead of threads, but processes don't share memory by default, so if you want to share e.g. sprites it's easier with threads.
If you have some performance heavy code, you can also write it in C or in Cython and then nothing the threads from running at the same time (as long as you release the global interpreter lock).