如何在Python中使用线程控制三个不同的线程?



我有thread1, thread2和thread3,全局变量x和三个不同的函数来增加x

import threading
import time
#check = threading.Condition()
x=1
def add_by1():
global x
x+=1
time.sleep(1)
print(x)

def add_by2():
x+=2
time.sleep(1)
print(x)
def add_by3():
x+=3
time.sleep(1)
print(x)
if __name__==__main__:
threading.Thread(target=add_by1).start()
threading.Thread(target=add_by2).start()
threading.Thread(target=add_by3).start()
# I want the output should print.. 
"""
2
4
7
8
10
13
14
16
19
and so on ..
"""

我可以使用Condition(),如果可以,如何使用?我可以使用其他线程类吗?,如何在这些函数中插入一些代码?

我想这种方法是可靠的。您可以使用三个lock对象同步线程——每个对象一个。

这个设置的工作方式是每个线程获得它的锁,并在完成它的工作后,它释放下一个线程的锁!然后,add_by1释放thread_lock_two,add_by2释放thread_lock_three,最后add_by3释放thread_lock_one

一开始你需要获得thread_lock_twothread_lock_three的锁,这样只有第一个线程完成它的工作。

无论何时满足条件(您说的x == 20),每个线程都应该再次释放下一个线程的锁return!

import threading
from time import sleep
x = 1
thread_lock_one = threading.Lock()
thread_lock_two = threading.Lock()
thread_lock_three = threading.Lock()
thread_lock_two.acquire()
thread_lock_three.acquire()

def add_by1():
global x
while True:
thread_lock_one.acquire()
if x >= 20:
thread_lock_two.release()
return
x += 1
print(x)
sleep(0.6)
thread_lock_two.release()

def add_by2():
global x
while True:
thread_lock_two.acquire()
if x >= 20:
thread_lock_three.release()
return
x += 2
print(x)
sleep(0.6)
thread_lock_three.release()

def add_by3():
global x
while True:
thread_lock_three.acquire()
if x >= 20:
thread_lock_one.release()
return
x += 3
print(x)
sleep(0.6)
thread_lock_one.release()

if __name__ == "__main__":
threading.Thread(target=add_by1).start()
threading.Thread(target=add_by2).start()
threading.Thread(target=add_by3).start()

输出:

2
4
7
8
10
13
14
16
19
20

最新更新