Python 线程:第二个线程等待第一个线程完成

问题描述 投票:0回答:2

我对 Python 线程还很陌生,但仍然无法使其正常工作。我不明白为什么,但线程是连续执行的,而不是并行执行的。

任何人都可以提出建议,代码中有什么不正确的地方(我尽可能地简化它以使其更接近示例,但它没有按预期工作):

import threading, time

def func1():
    for j in range (0, 10):
        print(str(time.ctime(time.time())) + " 1")
        time.sleep(0.5)


def func2():
    for j in range (0, 10):
        print(str(time.ctime(time.time())) + " 2")
        time.sleep(0.5)

print(str(time.ctime(time.time())) + " script started")

t1 = threading.Thread(target = func1(), name = " 1")
t2 = threading.Thread(target = func2(), name = " 2")

t1.start()
t2.start()

t1.join()
t2.join()

print (str(time.ctime(time.time())) + " over")

在控制台输出中,我看到第二个线程仅在第一个线程完成后才启动。我尝试使线程成为守护进程,删除 .join() 行,但仍然没有成功。

python python-3.x python-multithreading
2个回答
3
投票

我想指出这样一个事实:它们定义的 threading.Lock 对象和条件同步对象与“with 语句”一起使用,因为它们支持上下文管理协议:

lock = threading.Lock() # After: import threading
with lock:
    # critical section of code
    ...access shared resources...

这里,上下文管理机制保证在块执行之前自动获取锁,并在块完成后释放锁,无论异常结果如何。 因此,Vincent 上面建议的解决方案似乎正在解决一个更复杂的问题,该问题涉及在共享公共资源上放置锁,停止任何其他试图访问其轨道中的资源的线程(事实上,停止任何正在访问该资源的线程)尝试获取相同的锁)。注意:threading.Lock有两种状态:锁定和解锁,并且它是在解锁状态下创建的。下面以只有一个线程可以更新全局变量“count”为例:

import threading, time
count = 0
def adder(addlock): # shared lock object passed in
    global count
    with addlock:
        count = count + 1 # auto acquire/release around stmt
    time.sleep(0.5)
    with addlock:
        count = count + 1 # only 1 thread updating at any time
addlock = threading.Lock()
threads = []
for i in range(100):
    thread = threading.Thread(target=adder, args=(addlock,))
    thread.start()
    threads.append(thread)
for thread in threads: thread.join()
print(count)

我建议使用多处理的另一种解决方案,因为您的两个并行函数基本上是两个单独的进程,不需要访问任何共享资源。

from multiprocessing import Process
import time

def func1():
    for j in range (0, 10):
        print(str(time.ctime(time.time())) + " 1")
        time.sleep(0.5)

def func2():
    for j in range (0, 10):
        print(str(time.ctime(time.time())) + " 2")
        time.sleep(0.5)

if __name__ == '__main__':
    print(str(time.ctime(time.time())) + " script started")
    p1 = Process(target=func1)
    p1.start()
    p2 = Process(target=func2)
    p2.start()
    p1.join()
    p2.join()
    print (str(time.ctime(time.time())) + " over")

3
投票

您正在呼叫您的目标 (

target=func1()
)。相反,请执行以下操作:

t1 = threading.Thread(target=func1, name = "1")
t2 = threading.Thread(target=func2, name = "2")

编辑:这就是锁定打印的方式:

import threading, time

def func1(lock):
    for j in range (10):
        with lock:
            print(str(time.ctime(time.time())) + " 1")
        time.sleep(0.5)


def func2(lock):
    for j in range (10):
        with lock:
            print(str(time.ctime(time.time())) + " 2")
        time.sleep(0.5)

lock = threading.Lock()
t1 = threading.Thread(target = func1, name = " 1", args=(lock,))
t2 = threading.Thread(target = func2, name = " 2", args=(lock,))
© www.soinside.com 2019 - 2024. All rights reserved.