Ac3
Ac3

Reputation: 55

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

Upvotes: 1

Views: 209

Answers (1)

John Anderson
John Anderson

Reputation: 39082

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()

Upvotes: 3

Related Questions