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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.