Python 3 |多线程在清除thread.start()之前开始

时间:2019-04-14 21:14:30

标签: python python-3.x multithreading

尝试同时运行2种方法。一种是计时器方法,另一种是将数据写入CSV。我正在尝试使用Treading一次运行它们,但是线程在调用之前就开始了。

代码;


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

控制台的输出;

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

有人可以帮我解决这个问题吗?

谢谢

1 个答案:

答案 0 :(得分:3)

除非您想立即运行该方法,否则不要使用()。如果要引用方法本身(例如将其传递给Thread),请不要使用()。 尝试以下代码:

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