我正在研究Python 3上的线程。动机是在键盘中断时运行循环。
Thread.run()=>它开始我的循环,但没有结束于键盘中断。 Thread.start()=>仅循环一次,然后停止。
import threading as td
global run
run = True
def printThread():
global run
while run:
print('Hello world! run = ', run)
if __name__ == '__main__' :
thread1 = td.Thread(target=printThread, name='t1')
thread1.start()
input()
print(run)
run = False
thread1.join()
print('got it')
input()
除了运行我在c ++线程中工作的代码外。
#include <iostream>
#include <thread>
static bool run = true;
void dowork()
{
while(run)
std::cout << "hello";
}
int main()
{
std::thread worker(dowork);
std::cin.get();
run = false;
worker.join();
std::cin.get();
}