2018-11-27 11:31:35 +01:00
|
|
|
"""
|
|
|
|
Use a Timer to react to events in another thread
|
|
|
|
------------------------------------------------
|
|
|
|
|
|
|
|
You should never modify Blender data at arbitrary points in time in separate threads.
|
|
|
|
However you can use a queue to collect all the actions that should be executed when Blender is in the right state again.
|
|
|
|
Pythons `queue.Queue` can be used here, because it implements the required locking semantics.
|
|
|
|
"""
|
|
|
|
import bpy
|
|
|
|
import queue
|
|
|
|
|
|
|
|
execution_queue = queue.Queue()
|
|
|
|
|
2022-04-20 07:10:14 +02:00
|
|
|
|
2021-11-17 00:44:04 +01:00
|
|
|
# This function can safely be called in another thread.
|
2018-11-27 11:31:35 +01:00
|
|
|
# The function will be executed when the timer runs the next time.
|
|
|
|
def run_in_main_thread(function):
|
|
|
|
execution_queue.put(function)
|
|
|
|
|
2021-07-06 04:05:27 +02:00
|
|
|
|
2018-11-27 11:31:35 +01:00
|
|
|
def execute_queued_functions():
|
|
|
|
while not execution_queue.empty():
|
|
|
|
function = execution_queue.get()
|
|
|
|
function()
|
2018-11-27 20:09:42 +01:00
|
|
|
return 1.0
|
2018-11-27 11:31:35 +01:00
|
|
|
|
2021-07-06 04:05:27 +02:00
|
|
|
|
2018-11-27 11:31:35 +01:00
|
|
|
bpy.app.timers.register(execute_queued_functions)
|