3

All the examples I've been able to get to don't really address my problem, of having a certain procedure in the background constantly looping, while the rest of the program continues.

Here is a simple example of a method that works, using _thread:

import _thread
import time


def countSeconds():
    time.sleep(1)
    print("Second")
    _thread.start_new(countSeconds, ())

def countTenSeconds():
    time.sleep(10)
    print("Ten seconds passed")
    _thread.start_new(countTenSeconds, ())


_thread.start_new(countSeconds, ())
_thread.start_new(countTenSeconds, ())

Ignoring the obvious fact that we could track the seconds, and just print something different if it's a multiple of ten, how would I go about creating this more efficiently.

In my actual program, the threading seems to be guzzling RAM, I assume from creating multiple instance of the thread. Do I have to "start_new" thread at the end of each procedure?

Thanks for any help.

Constantly Confused
  • 595
  • 4
  • 10
  • 24
  • Re-calling a thread in itself doesn't seem really reasonable, maybe something like this is what you need: http://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds – Philip Feldmann Jan 12 '16 at 16:59
  • Is there any reason you're not using the [threading](https://docs.python.org/2/library/threading.html) module? It will be simpler than using the low-level [_thread](https://docs.python.org/3.1/library/_thread.html) module. Also, thanks to the [GIL](https://wiki.python.org/moin/GlobalInterpreterLock), threaded Python applications are not actually parallel - you need [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) for that. – skrrgwasme Jan 12 '16 at 17:03

2 Answers2

5

All the examples I've been able to get to don't really address my problem Which examples?

This does work for me.

import threading

def f():
    import time
    time.sleep(1)
    print "Function out!"

t1 = threading.Thread(target=f)

print "Starting thread"
t1.start()
time.sleep(0.1)
print "Something done"
t1.join()
print "Thread Done"

You're asking for a repeated thread, I don't get what exactly you need, this might work:

import threading
var = False
def f():
    import time
    counter = 0
    while var:
        time.sleep(0.1)
        print "Function {} run!".format(counter)
        counter+=1

t1 = threading.Thread(target=f)

print "Starting thread"
var = True
t1.start()
time.sleep(3)
print "Something done"
var = False
t1.join()
print "Thread Done"
tglaria
  • 5,678
  • 2
  • 13
  • 17
3

use the threading.timer to continue launching a new background thread

import threading
import time


def countSeconds():
    print("Second")
    threading.Timer(1, countSeconds).start()

def countTenSeconds():
    print("Ten seconds passed")
    threading.Timer(10, countTenSeconds).start()


threading.Timer(1, countSeconds).start()
threading.Timer(10, countTenSeconds).start()
Freakin
  • 76
  • 4