views:

157

answers:

4

Hello,

I have a script and I want one function to run at the same time as the other.

Example code I have looked at:

import threading


def MyThread ( threading.thread ):

  doing something........

def MyThread2 ( threading.thread ):

  doing something........

MyThread().start()
MyThread2().start()

I am having trouble getting this working. I would prefer to get this going using a threaded function rather than a class.

Thanks for any help.

This is the working script, Thanks for all the help.

class myClass():

    def help(self):

        os.system('./ssh.py')

    def nope(self):
        a = [1,2,3,4,5,6,67,78]
        for i in a:
            print i
            sleep(1)


if __name__ == "__main__":
    Yep = myClass()
    thread = Thread(target = Yep.help)
    thread2 = Thread(target = Yep.nope)
    thread.start()
    thread2.start()
    thread.join()
    print 'Finished'
+1  A: 

Did you override the run() method? If you overrided __init__, did you make sure to call the base threading.Thread.__init__()?

After starting the two threads, does the main thread continue to do work indefinitely/block/join on the child threads so that main thread execution does not end before the child threads complete their tasks?

And finally, are you getting any unhandled exceptions?

Jeremy Brown
@Jeremy Brown -- There are no unhandled exceptions and the main thread should run for 30mins. I did not override `__init__`. Is run() required then? Thanks
chrissygormley
I just realized that your example is `def MyThread ( threading.thread )`... I assumed that those were class definitions. If you are going to subclass threading.thread and initialize the thread object with `target=None` or omit the `target` arg, then an implementation of run() is required. Otherwise, if you just want to run a simple task in another thread, see jkp's answer.
Jeremy Brown
+1  A: 

You can use the target argument in the Thread constructor to directly pass in a function that gets called instead of run.

unholysampler
+4  A: 

You don't need to use a subclass of Thread to make this work - take a look at the simple example I'm posting below to see how:

from threading import Thread
from time import sleep

def threaded_function(arg):
    for i in range(arg):
        print "running"
        sleep(1)


if __name__ == "__main__":
    thread = Thread(target = threaded_function, args = (10, ))
    thread.start()
    thread.join()
    print "thread finished...exiting"

Here I show how to use the threading module to create a thread which invokes a normal function as its target. You can see how I can pass whatever arguments I need to it in the thread constructor.

jkp
@jkp -- I have tried this. I have added script up above. Could you tell me how to get the second function running alongside the first one. Thanks
chrissygormley
@chrissygormley: join() blocks until the first thread finishes.
FogleBird
@chrissygormley: as mentioned, join blocks until the thread you are joining finishes, so in your case, start a second thread with your second function as a target to run the two functions side-by-side, then optionally join one of them if you just want to wait until they are done.
jkp
@jkp -- Got it working, thanks alot for the help. Help's me get a better idea of threads in python. +1
chrissygormley
+5  A: 

There are a few problems with your code:

def MyThread ( threading.thread ):
  • You can't subclass with a function; only with a class
  • If you were going to use a subclass you'd want threading.Thread, not threading.thread

If you really want to do this with only functions, you have two options:

With threading:

import threading
def MyThread1():
    pass
def MyThread2():
    pass

t1 = threading.Thread(target=MyThread1, args=[])
t2 = threading.Thread(target=MyThread2, args=[])
t1.start()
t2.start()

With thread:

import thread
def MyThread1():
    pass
def MyThread2():
    pass

thread.start_new_thread(MyThread1, [])
thread.start_new_thread(MyThread2, [])
Jorenko