运行 python 同时有一个函数和一个线程

Running a function and a thread at a same time in python

我的应用程序需要同时 运行 一个函数和一个线程。我在函数内创建了一个线程并启动了该线程。我尝试同时 运行 函数和线程,我想停止线程,直到函数内部的某些条件得到满足。但是线程 运行 首先直到它完成,然后只有函数开始执行。我无法实现并发。

这是我的代码

import threading
from time import sleep
start_threads = False
stop_threads = True
def testthread():
    global stop_threads
    k = 0
    while k < 100:
        print("testthread -->",k)
        k += 1
        sleep(1)
        if k == 100:
            stop_threads = True
            if stop_threads:
                break
            
        


def testfunction():
    global stop_threads   
    t1 = threading.Thread(target = testthread)
    t1.start()
    i = 0
    while i < 100:
        print("testfunction-->",i)
        i += 1
        sleep(1)
        if i == 100:
            stop_threads = False
        if stop_threads:
            t1.join()
            print('thread killed')
        

testfunction()

我试图让输出像....

testthread --> 0
testthread --> 1
.
.
.
testthread --> 99
thread killed
testfunction--> 1
thread killed
'
'
'
testfunction--> 98
thread killed
testfunction--> 99
>>> 

我希望输出像..

>>>
testthread --> 0
testfunction --> 0
testthread --> 1
testfunction --> 1
'
'
'
testthread -->99
threadkilled
testfunctionn -->99

首先,您开始时 stop_threads 为 True,因此 main 函数只是在一次迭代后将其删除,然后等待您开始完成的线程。

这不是查看同一个全局,您不能只让多个线程查看同一个全局并期望它是线程安全的。但是,如果您简化代码,就会发现根本不需要这样做:

import threading
from time import sleep


def testthread():
    k = 0
    while k < 3:
        print("testthread -->", k)
        k += 1
        sleep(1)


def testfunction():
    t1 = threading.Thread(target=testthread)
    t1.start()
    i = 0
    while i < 5:
        print("testfunction-->", i)
        i += 1
        sleep(1)
    t1.join()


testfunction()

输出:

testthread --> 0
testfunction--> 0
testfunction--> 1
testthread --> 1
testfunction--> 2
testthread --> 2
testfunction--> 3
testfunction--> 4

线程在调用 sleep() 时有效地相互让步,因此代码按预期工作,如果您使用值 < 3< 5,您我会看到两者都可以完成。