Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 带有';而';有另一个线程从未启动_Python_Multithreading - Fatal编程技术网

Python 带有';而';有另一个线程从未启动

Python 带有';而';有另一个线程从未启动,python,multithreading,Python,Multithreading,我试着每1秒添加一个数字,然后每3秒监视结果2次。我尝试在python中使用线程,但当一个线程正在运行时,另一个线程永远不会启动 import threading, time a = 0 def a1(): print('adding') global a while a < 1000: a+=1 print('a from a1', a) time.sleep(1) def showprogress():

我试着每1秒添加一个数字,然后每3秒监视结果2次。我尝试在python中使用线程,但当一个线程正在运行时,另一个线程永远不会启动

import threading, time

a = 0
def a1():
    print('adding')
    global a
    while a < 1000:
        a+=1
        print('a from a1', a)
        time.sleep(1)


def showprogress():
    global a
    print(a)
    time.sleep(3)
    print(a)
    time.sleep(3)
    print(a)

t1 = threading.Thread(target=a1())
t2 = threading.Thread(target=showprogress())
t1.start()
t2.start()

showprogress函数永远不会执行

这应该可以工作。您的函数之所以没有,是因为您正在将函数
a1()
传递到目标中
target
接收一个可调用对象,因此通过在内部传递整个函数,您实际上要做的是传递返回值,在本例中为
None
showprogress()
将在
a()
之后执行,这也将
None
传递到参数中

如果您想将参数传递到函数中,您可以做的是

t1=threading.Thread(target=a1,args=(4,0.25))
(如果您的函数接受参数)

导入线程,时间
a=0
def a1():
打印('添加')
全球a
当a<1000时:
a+=1
打印('a1'中的a',a)
时间。睡眠(1)
def showprogress():
全球a
印刷品(a)
时间。睡眠(3)
印刷品(a)
时间。睡眠(3)
印刷品(a)
t1=线程。线程(目标=a1)
t2=线程。线程(目标=显示进度)
t1.start()
t2.start()
t1.join()
t2.join()

@EdelWang嗨,你的错误不是
.join()
它传入的是
a1()
的参数,而不是
a1
.join()
基本上意味着线程将在其完成后连接回主线程,以便它正确退出。@EdelWang如果您认为这解决了您的问题,您可以接受这一点。
adding
a from a1 1
a from a1 2
a from a1 3
a from a1 4
a from a1 5
a from a1 6
a from a1 7
a from a1 8
import threading, time

a = 0
def a1():
    print('adding')
    global a
    while a < 1000:
        a+=1
        print('a from a1', a)
        time.sleep(1)


def showprogress():
    global a
    print(a)
    time.sleep(3)
    print(a)
    time.sleep(3)
    print(a)

t1 = threading.Thread(target=a1)
t2 = threading.Thread(target=showprogress)
t1.start()
t2.start()
t1.join()
t2.join()