【问题标题】:How can I control three different threads using threading in Python?如何在 Python 中使用线程控制三个不同的线程?
【发布时间】:2022-12-22 01:16:37
【问题描述】:

我有 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()吗?如果可以的话怎么办?我可以使用其他线程类吗?如何在这些函数上插入一些代码?

【问题讨论】:

  • 你想用threading.Condition做什么?您是否在多线程环境中阅读过what a Condition does
  • 我只是想也许它会解决问题

标签: python multithreading variables global python-multithreading


【解决方案1】:

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

此设置的工作方式是每个线程获取它的锁,完成它的工作后,它释放下一个线程的锁! IOW,add_by1发布thread_lock_twoadd_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

【讨论】:

  • 那我怎么能杀死线程呢?当满足 x 的特定值时,我可以执行 quit() 吗?
  • @fardV 我用另一种方法重写了答案。这样,当满足条件或例如 x 达到 20 时,线程将被终止。
  • 非常有创意和惊人!非常感谢您解决这个问题!!
猜你喜欢
  • 2011-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-14
  • 2014-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多