Created
September 15, 2019 02:49
-
-
Save drmfinlay/37114026a4adc331a1c0d5cc44506c57 to your computer and use it in GitHub Desktop.
Natlink thread example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Natlink doesn't usually work well with other threads because of how it | |
# works internally. This example command module demonstrates a workaround | |
# for this problem using a Dragonfly timer and Thread.join(). | |
# | |
# This workaround can work using the natlink.setTimerCallback() function | |
# directly instead. | |
# | |
# Copy this file into the natlink MacroSystem folder to try it out. | |
import threading | |
import time | |
from dragonfly import get_engine | |
# Initialise and start a new thread that prints a message every five | |
# seconds. | |
shutdown_event = threading.Event() | |
def run(): | |
thread_name = threading.current_thread().name | |
while not shutdown_event.is_set(): | |
print("Output from %s" % thread_name) | |
time.sleep(5) | |
print("%s exiting..." % thread_name) | |
thread = threading.Thread(target=run) | |
thread.start() | |
# Initialise a dragonfly timer to manually yield control to the thread. | |
def timer_func(): | |
thread.join(0.002) | |
timer = get_engine().create_timer(timer_func, 0.02) | |
def unload(): # Natlink unload() function. | |
# Set the shutdown event and wait for the thread to finish. | |
shutdown_event.set() | |
thread.join() | |
# Stop the timer now that the thread has finished. | |
timer.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment