nonsensei
nonsensei

Reputation: 480

python - linux - starting a thread immediately

here's some example code

while True: #main-loop
    if command_received:
        thread = Thread(target = doItNOW)
        thread.start()

...... 


def doItNOW():
    some_blocking_operations()

my problem is I need "some_blocking_operations" to start IMMEDIATELY (as soon as command_received is True). but since they're blocking i can't execute them on my main loop and i can't change "some_blocking_operations" to be non-blocking either

for "IMMEDIATELY" i mean as soon as possible, not more than 10ms delay. (i once got a whole second of delay). if it's not possible, a constant delay would also be acceptable. (but it MUST be constant. with very few milliseconds of error)

i'm currently working on a linux system (Ubuntu, but it may be another one in the future. always linux)

a python solution would be amazing.. but a different one would be better than nothing

any ideas? thanks in advance

Upvotes: 1

Views: 115

Answers (1)

Torxed
Torxed

Reputation: 23500

from threading import Thread
class worker(Thread):
    def __init__(self, someParameter=True):
        Thread.__init__(self)
        # This is how you "send" parameters/variables
        # into the thread on start-up that the thread can use.
        # This is just an example in case you need it.
        self.someVariable = someParameter
        self.start() # Note: This makes the thread self-starting,
                     #       you could also call .start() in your main loop.
    def run():
        # And this is how you use the variable/parameter
        # that you passed on when you created the thread.
        if self.someVariable is True:
            some_blocking_operations()

while True: #main-loop
    if command_received:
        worker()

This is a non-blocking execution of some_blocking_operations() in a threaded manner. I'm not sure if what you're looking for is to actually wait for the thread to finish or not, or if you even care?

If all you want to do is wait for a "command" to be received and then to execute the blocking operations without waiting for it, verifying that it completes, then this should work for you.

Python mechanics of threading

Python will only run in one CPU core, what you're doing here is simply running multiple executions on overlapping clock invervals in the CPU. Meaning every other cycle in the CPU an execution will be made in the main thread, and the other your blocking call will get a chance to run a execution. They won't actually run in parallel.

There are are some "You can, but..." threads.. Like this one:

Upvotes: 1

Related Questions