线程时不执行的函数

时间:2015-11-29 16:56:15

标签: python multithreading python-2.7

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

MODULE 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()

MODULE2

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,())

1 个答案:

答案 0 :(得分:2)

你在一个线程中启动编译器,但它调用class_often,因为它是一个无限循环而阻塞,所以第二个函数不能被调用:

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

你需要在thread.start_new_threadd.complier,即:

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.
...........................

threading lib也建议使用thread lib。

相关问题