0

I'm looking at running some code to auto-save a game every X minutes but it also has a thread accepting keyboard input. Here's some sample code that I'm trying to get running simultaneously but it appears they run one after the other. How can I get them to run at the same time?

import time
import threading

def countdown(length,delay):
    length += 1
    while length > 0:
        time.sleep(delay)
        length -= 1
        print(length, end=" ")

countdown_thread = threading.Thread(target=countdown(3,2)).start()
countdown_thread2 = threading.Thread(target=countdown(3,1)).start()

Update: Not sure really what the difference python has between a process and a thread (would process show as a second process in Windows?) But here's my updated code. It still runs sequentially and not at the same time.

import time
from threading import Thread
from multiprocessing import Process

def countdown(length,delay):
    length += 1
    while length > 0:
        time.sleep(delay)
        length -= 1
        print(length, end=" ")

p1 = Process(target=countdown(5,0.3))
print ("")
p2 = Process(target=countdown(10,0.1))
print ("")
Thread(target=countdown(5,0.3))
print ("")
Thread(target=countdown(10,0.1))
1
  • You may want to add a flush=True to that print statement to make it more obvious what is happening. Commented Jun 23, 2022 at 16:13

2 Answers 2

2

When you create the threads, they should be created as

Thread(target=countdown, args=(3,2))

As-is, it runs countdown(3,2), and passes the result as the Thread target!

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

2 Comments

So I have Thread(target=countdown(5,0.5)).start() Thread(target=countdown(10,0.1)).start() and they still don't run at the same time. It waits for one to finish before starting the other.
you need to set the target as the name of the function, without (), which calls it! args or kwargs ("keyword args") must be passed to Thread, not the function .. if you call the function with (), it passes the result (None) like .Thread(target=None)
-1

AFAIK Threads cant run simultainously.

I suggest you take a look at multiprocessing instead: https://docs.python.org/3/library/multiprocessing.html

1 Comment

this depends on how you slice such a thing; threads can and do run concurrently, but many operations are blocked by the GIL (and so it's worth understanding the differences, really verifying if there is some speedup, and also whether multiprocessing requires a lot of data to be copied)! both threads and processes are otherwise scheduled by the operating system (as each processor can only do discrete amounts of work at once)

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.