线程化时不执行的函数

2024-07-07 07:57:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了两个模块,其中包含一些函数。我在module1中的一个函数中包含了两个函数,在module2中导入了module1,编译器中包含的函数often1似乎没有执行

模块1

import time,thread

def class_often():
    while 1<2:
        time.sleep(5)
        print "Custom funtion not often runs."

def class_often1():
    while 1<2:
        time.sleep(2)
        print "Custom funtion often runs."

def compiler():
    class_often()
    class_often1()

模块2

import time,d,thread

def often():
    while 1<2:
        time.sleep(2)
        print "funtion not often runs."

def often1():
    while 1<2:
        time.sleep(2)
        print "Function often runs."

thread.start_new_thread(often,())
thread.start_new_thread(often1,())
thread.start_new_thread(d.compiler,())

Tags: 模块函数newtimedefrunssleepthread
1条回答
网友
1楼 · 发布于 2024-07-07 07:57:10

在线程中启动编译器,但它调用class_often,因为它是一个无限循环,所以无法调用第二个函数:

def compiler():
    class_often() # blocks
    class_often1()

您还需要在d.complierthread.start_new_thread,即:

def class_often():
    while True:
        time.sleep(5)
        print("Custom funtion not often runs.")


def class_often1():
    while True:
        time.sleep(2)
        print("Custom funtion often runs.")


def compiler():
    thread.start_new_thread(class_often,())
    class_often1()

更改后会产生如下输出:

funtion not often runs.
Custom funtion often runs.
Function often runs.
Custom funtion not often runs.
funtion not often runs.
Custom funtion often runs.
Function often runs.
funtion not often runs.
Custom funtion often runs.
Function often runs.
funtion not often runs.
Custom funtion often runs.
Function often runs.
...........................

thread库上也建议使用threading lib

相关问题 更多 >