python - 线程处理时未执行的函数

标签 python multithreading python-2.7

我创建了两个模块,其中有一些功能。我在 module1 中的单个函数中包含了 2 个函数,并在 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,())

最佳答案

您在线程中启动编译器,但它调用 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.
...........................

threading lib还建议使用 thread 库。

关于python - 线程处理时未执行的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33985365/

相关文章:

android - 使用kivy/python访问android手电筒(相机LED闪光灯)

python - 堆叠子图的对齐

python - 谷歌应用引擎过多的数据存储小操作

C++:如果 std::atomic_flag 是唯一的无锁原子类型,如何在 C++ 中实现无锁数据结构?

python - 在 Python 中调用 exit() 时,C++ 析构函数中的互斥锁会导致异常

python - pyinstaller,导入错误: no module named pywintypes

python - flask-sqlalchemy 中的奇怪过滤器行为

python - 重复 numpy 数组

python-2.7 - 使用 scrapy 从 Flipkart 上抓取数据

android - 为什么打开 proguard 的 "Surface frame wait timed out"编码?