How to delay a part of my program without affecting the rest?

此生再无相见时 提交于 2020-01-15 05:25:49

问题


I have a program in which I utilize a score counter. That score counter is initially 100 and stays like that until a certain threshold is crossed. The threshold variable is called shipy and my score is called score.

I implemented something that subtracts 1 from my score every 0.1s once shipy is over 400, but doing it like that causes my whole program to run slower.

Here a snippet of my code:

shipy = 0
score = 100

# some code here doing something, eg. counting shipy up

if shipy > 400:
    time.sleep(0.1)
    global score
    score-=1

# more code doing something else

Is there a way to run that score subtraction independently of the rest of the code?


回答1:


You need to use a different thread for your score calculation. Just start a new thread for counting down your score.

import threading
import time

def scoreCounter(): 
    while shipy > 400:
        time.sleep(0.1)
        global score
        score-=1

t1 = threading.Thread(target=scoreCounter) 

Then just call t1.start() at some point in the code if shipy > 400.




回答2:


Have a look to this multi-threading program.

  • The main program prints "Here you can do other stuff" and then waits for you to press Enter
  • Another function in parallel is incrementing a variable i and printing it

I let you try this :

import threading
import time

def main_function():
    global continuer_global, i
    i = 0
    t1 = threading.Thread(target = counter)
    t1.daemon = True # With this parameter, the thread functions stops when you stop the main program
    t1.start()
    print("Here you can do other stuff")
    input("Press Enter to exit program\n")

def counter ():
    # Do an action in parallel
    global i
    while True:
        print("i =", i)
        i += 1
        time.sleep(1)

main_function()



回答3:


You need to have your program in a "run to completion" style.

So, given a time_now() function which returns the current time in seconds, you can write some code like this:

prev_time = time_now()
while True:
    run_program()   # Your program runs and returns
    curr_time = time_now()
    if curr_time - prev_time >= 1:
        prev_time += 1
        if shipy > 400:
            score -= 1

This way your code in run_program() gets to do what it has to, but returns as soon as it can. The rest of the code above never loops round waiting for time, but instead only runs when it should.

Once the score has been dealt with you can see that run_program() is called again.

This just shows the principle. In practise you should incorporate the checks for shipy inside the run_program() function.

Also, this runs in a single thread, so there are no semaphores needed to access shipy or score.



来源:https://stackoverflow.com/questions/59412769/how-to-delay-a-part-of-my-program-without-affecting-the-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!