2

I wanted to run a function repeating itself while my main code (I guess it is called main thread) is still running so I did this, there is probably a better way of doing this but I am new to coding and python so I have no idea what am I doing.

import threading
import time

def x():
    print("hey")
    time.sleep(1)
    x()
t = threading.Thread(target=x)
t.daemon = True
t.start()

when I make daemon False it repeats itself but when I stop the program I get an error

Darkonaut
  • 20,186
  • 7
  • 54
  • 65
EymenKc
  • 21
  • 1

1 Answers1

1

CPython (the reference implementation of Python) does not implement Tail Call Optimization (TCO).¹ This means you can't run excessive recursion since it is limited and you would get a RuntimeError when you hit this limit.

sys.getrecursionlimit() # 3000

So instead of calling x() from within x() again, make a while True-loop within x():

import threading
import time

def x():
    while True:
        print("hey")
        time.sleep(1)

t = threading.Thread(target=x, daemon=True)
t.start()
time.sleep(10)  # do something, sleep for demo

¹ Stackless Python would be a Python implementation without recursion limit.

Darkonaut
  • 20,186
  • 7
  • 54
  • 65
  • I want to understand how threading works, I am trying to write a clicker game for practice and I feel like I need to use threading for auto clicker (basically I have created a variable called gold and auto clicker will add 1 to gold every second). I am using turtle module too btw. I created a thread for this but when I run the program gold value doesn't go up unless I move my mouse or press any keys, I have no idea why this is happening. – EymenKc Dec 08 '19 at 01:50
  • @EymenKc I can't tell you how to write your clicker game, but a thread could do that specific task in principle. If `gold` is a global variable, you would have to declare `global gold` within your function first before you define and use it. For how "threading works", familiarize yourself with the [GIL](https://wiki.python.org/moin/GlobalInterpreterLock). – Darkonaut Dec 08 '19 at 02:11