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



我对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()行,但仍然没有成功。

我想指出一个事实,即线程。他们定义的锁定对象和条件同步对象与"with语句"一起使用,因为它们支持上下文管理协议:

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

这里,上下文管理机制保证在执行块之前自动获取锁,并在块完成后释放锁,而不管异常结果如何。因此,Vincent提出的上述解决方案似乎是在解决一个更复杂的问题,即在共享的公共资源上设置锁,停止任何其他试图访问其轨道上的资源的线程(事实上,停止任何试图获取相同锁的线程)。注:螺纹。锁定有两种状态:锁定和解锁,并且它是在解锁状态下创建的。例如,在下面的例子中,由于只有一个线程可以更新全局变量"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")

您正在调用您的目标(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,))

最新更新