0

So I have a terrible little code here

import threading
import time
hours, mins, secs, = 0,0,0


def countUp():
    # so I can get data from get_time
    global hours, mins, secs

    # a game clock thats meant to run in the background
    while True:
        # if mins and secs are 59, add an hour
        if mins == 59 and secs == 59:
            hours += 1
        # if not, don't add anything
        else:
            hours += 0

        # adds a minute when 60 seconds is up (if its 59, it'll print 60 idk why)
        if secs == 59:
            mins += 1
        # after 60 seconds is up, mins would reset to 0 otherwise
        elif mins <= 59:
            mins += 0
        # when mins == 60, reset to 0
        else:
            mins = 0

        # adds a seconds while a minute isn't up
        if secs <= 58:
            secs += 1
        else:
            # resets seconds when a minute is up
            secs = 0

        time.sleep(1)

def get_time():
    # get time from countUp
    global hours, mins, secs
    # print it
    print(f'{hours}:{mins}:{secs} passed')

counter = threading.Thread(target=countUp())
counter.start()

print('This is the base code')
get_time()

It is very scuffed but does the job. If I run it though, the thread works but nothing below counter.start() runs. I tried changing the while true loop to a for loop and the main program runs after the function has finished.

I put the main program in a function of it's own and threaded it, but nothing changed.

As for multiprocessing, I don't know what I did but countUp didn't seem to have called. I did import multiprocessing and change

counter = threading.Thread(target=countUp())
counter.start()

to

if __name__ == '__main__':
    p = multiprocessing.Process(target=countUp, args=())
    p.start()
    p.join()

ps. i know this code is very bad

  • what a so complicated way with so many tests to add 1 sec to secs mins and hours ? – bruno Dec 26 '20 at 16:24
  • `counter = threading.Thread(target=countUp())` --> `counter = threading.Thread(target=countUp)` – wwii Dec 26 '20 at 16:37
  • bruno when I wrote the function, I wasn't really, you know, _thinking_. I was randomly changing stuff til it worked –  Dec 26 '20 at 16:52
  • Even with `target=countUp`, this code is never going to do anything interesting. It will print "This is the base code. 0:0:1 passed" and then spin endlessly in a blocking while-loop until you kill it. You cannot get truly parallel threading in python with cpu-bound tasks (but you can with io-bound tasks). That is why multiprocessing is needed. But your script doesn't really do anything that could take advantage of that either. If you want to understand the pros and cons of the two approaches, you need to come up with a more coherent example. – ekhumoro Dec 26 '20 at 16:53
  • ekhumoro the idea is that I can use it with an actual game and at the end it can tell you how long it took you to complete it –  Dec 26 '20 at 17:14

0 Answers0