I'm making my first python program that uses multiple threads. Basically you have the main program, in this program by use of various widgets you can define how many threads you want to run and the details of how these threads will run, then you can click on a menu item to start or stop all of these threads at once. When you start they all start and when you stop it's a little more complicated.

In each of these threads I'm using os.system() to run a C program over and over until they are told to stop. Depending on the data you give to the C program it can take anywhere from a few seconds to a few hours to run. When the user chooses to stop the threads I want to give them two options, wait for the threads to finish the current execution of the C program, at which point they will check a flag to see if they should run the C program again or return, or to stop the execution of the C program and continue on. My problem is I'm not sure how I could stop the C program's process. Here is a small example of what I planned for the threads to look like, slightly simplified though

while True:
    os.system('name of program and command line arguments')#I want to be able to stop what ever this runs
    if self.control.stop:
        break

I give you a possible pattern (untested)

from subprocess import Popen
from threading import Condition
import os
import signal

self.user_condition = Condition()
...
self.user_condition.acquire()
try:
    while True:
        child = Popen("path/to/executable", *arguments)
        #http://docs.python.org/lib/node537.html
        self.user_condition.wait()
        if self.user_wants_to_exit_the_loop:
            if self.user_wants_to_stop_child:
                os.kill(child.pid, signal.SIGKILL)
                # http://docs.python.org/lib/os-process.html#l2h-2764
            elif self.user_wants_to_wait_for_child:
                child.wait() 
                #http://docs.python.org/lib/node532.html
            break
finally:
    self.user_condition.release()

you should also catch some exceptions. For example, os.kill may raise OSErrorr :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.