python - 一个带有 'while' 的线程 python 得到另一个线程从未启动

标签 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():
    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()

下面是输出

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

showprogress 函数永远不会被执行

最佳答案

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

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

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

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

关于python - 一个带有 'while' 的线程 python 得到另一个线程从未启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57532837/

相关文章:

python - 无法在 python 3.8 上将带有 webapp 的 python 部署到 azure

java - 我需要显式导入 Thread 类吗?

java - 同时合并列表 - CopyOnWriteArrayList 或 ConcurrentLinkedQueue 哪个更好?

python - 按属性字母数字排序对象列表

python - 使用 .grid 将 tkinter 列表框的大小调整为最大项目的宽度

python - 返回或中断作为 python 模拟中的副作用?

Java JAXB 多线程解码

python - 匹配整行的正则表达式

python - 使用线程初始化类 (Python)

java - 线程锁排序与简单的同步块(synchronized block)