以下是一个简单的示例源代码,演示了同一进程中两个线程的切换和控制:

import threading

# 全局变量,用于线程之间的通信
message = ""

# 线程1的执行函数
def thread1_func():
    global message
    while True:
        # 等待线程2的执行
        while message != "Thread2":
            pass
        # 执行线程1的任务
        print("Thread 1 is working")
        message = "Thread1"

# 线程2的执行函数
def thread2_func():
    global message
    while True:
        # 执行线程2的任务
        print("Thread 2 is working")
        message = "Thread2"
        # 等待线程1的执行
        while message != "Thread1":
            pass

# 创建线程1和线程2
thread1 = threading.Thread(target=thread1_func)
thread2 = threading.Thread(target=thread2_func)

# 启动线程1和线程2
thread1.start()
thread2.start()

# 等待线程1和线程2结束
thread1.join()
thread2.join()

在这个示例中,我们通过全局变量message实现了线程之间的通信。线程1和线程2分别执行不同的任务,并在完成任务后将message的值更新为对应的线程名称。通过循环判断message的值,实现了线程的切换和控制。

注意,示例代码中的线程是一个无限循环,需要手动停止线程的执行。在实际应用中,可能需要根据具体的需求进行适当的修改

同一进程的两个线程在工作中的切换和控制给一下示例源代码

原文地址: https://www.cveoy.top/t/topic/ixjS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录