简体   繁体   中英

Python 3 | Mutithreading starts before thread.start() is decleared

Trying to have 2 methods running at once. One is a timer method and the other writes data to a CSV. I am trying to use Treading to run them both at once, but the thread starts before it is called.

Code;


 with open("C:\\ProgramData\\Example.txt", "r", encoding="utf8") as file:
        array = for line in file.readlines()]))

    fieldnames = 'Col1','Col2','Col3'
    with open("C:\\ProgramData\\example.csv", 'w', newline='', encoding="utf8") as csvfile:
     writer = csv.writer(csvfile)
     writer.writerow(fieldnames)
     writer.writerows(array)
     csvfile.close()

def timer():
    import time
    import sys

    time_start = time.time()
    seconds = 0
    minutes = 0

    while True:
        try:
            sys.stdout.write("\r{minutes} Minutes {seconds} Seconds".format(minutes=minutes, seconds=seconds))
            sys.stdout.flush()
            time.sleep(1)
            seconds = int(time.time() - time_start) - minutes * 60
            if seconds >= 60:
                minutes += 1
                seconds = 0
        except KeyboardInterrupt as e:
            break

if __name__=="__main__":
    print("Not running")
    t1 = threading.Thread(target=timer())
    print("clearly running")
    t2 = threading.Thread(target=regx())
    t1.setName('t1')
    t2.setName('t2')

    t1.start()
    t2.start()

    t1.join()
    t2.join()
  # pool =Pool(processes=2)
  # pool.map(timer(),regx())

The output from the console;

Not running
2 Minutes 32 Seconds
Process finished with exit code -1

Can anyone help me fix this?

Thanks

Don't use () unless you want to run the method immediately. If you want to reference the method itself (like to pass it to Thread ), leave off the () . Try this code:

if __name__=="__main__":
    print("Not running")
    t1 = threading.Thread(target=timer)
    print("clearly running")
    t2 = threading.Thread(target=regx)
    t1.setName('t1')
    t2.setName('t2')

    t1.start()
    t2.start()

    t1.join()
    t2.join()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM