Global variables in python are entirely thread safe.
Sorry to disagree but this is true only if the global var is read-only, meaning you only read its value but never change it, or change it but only from one thread. The moment you change its value from 2 threads running in parallel you’re no longer thread safe, unless you use a synchronization mechanism (threading.Lock
, queue.Queue
and others).
I do agree though that if you use run_command()
, set_timeout()
and async_set_timeout()
there should never be be 2 commands / threads running in parallel (they run serially, one after another), so you should be fine. You have a problem only if you use threading.Thread()
directly (I do in some of my plugins).
Commands are also blocking, so there’s nothing to wait for.
I wanted to test this assertion and verified this is indeed true:
import time
import functools
import sublime
import sublime_plugin
class MyTestCommand(sublime_plugin.WindowCommand):
def run(self, **kwargs):
time.sleep(0.1)
print("result", kwargs)
class MyDummyCommand(sublime_plugin.WindowCommand):
def run(self):
for x in range(10):
fun = functools.partial(
self.window.run_command, "my_test", {"foo": x}
)
t = time.time()
sublime.set_timeout_async(fun, 0)
print("run_command returned in %.4f secs" % (time.time() - t))
Prints:
result {'foo': 0}
run_command returned in 0.1031 secs
result {'foo': 1}
run_command returned in 0.1034 secs
result {'foo': 2}
run_command returned in 0.1036 secs
result {'foo': 3}
run_command returned in 0.1039 secs
result {'foo': 4}
run_command returned in 0.1051 secs
result {'foo': 5}
run_command returned in 0.1029 secs
result {'foo': 6}
run_command returned in 0.1026 secs
result {'foo': 7}
run_command returned in 0.1035 secs
result {'foo': 8}
run_command returned in 0.1035 secs
result {'foo': 9}
run_command returned in 0.1037 secs
If you use set_timeout_async()
though, run_command()
returns immediately, so in that case I guess you’d still need a wait mechanism like the queue.Queue
example I pasted above.