使用Python中的多线程API时,在另一个.py文件
问题描述:
我的目标函数,我要在我的Python应用程序中使用线程。假设我想用下面的main.py文件代码在一个线程中运行工人()函数:使用Python中的多线程API时,在另一个.py文件
def threadcalling():
t = threading.Thread(target=worker())
threads.append(t)
t.start()
和work.py文件我的工人功能是像这样的:
def worker():
"""thread worker function"""
print 'Worker'
return
我问题:如果工人()函数是在我打电话的是同一个.py文件,每一件事情是确定的,但在我的主要脚本中使用,如果工人()函数中,我已经导入了另一种.py文件导入命令,我得到这个错误:
<type 'exceptions.ValueError'>
答
对于我来说,这个工程:
德德@酷睿i5:〜>猫bb.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading
from cc import *
threads=[]
t = threading.Thread(target=worker)
threads.append(t)
t.start()
德德@酷睿i5:〜>猫cc.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def worker():
"""thread worker function"""
print 'Worker'
return
德德@ I5: 〜>蟒蛇bb.py
Worker
对于从工人返回值(),使用GL obal变量(带锁)或队列。
请发表您的[** **齐全(https://stackoverflow.com/help/mcve)代码。另外,你为什么要手动管理线程?什么是错了['ThreadPool'(http://stackoverflow.com/a/3386632/35070)或['ThreadPoolExecutor'](https://docs.python.org/dev/library/concurrent.futures.html #threadpoolexecutor)? – phihag
它一般是可以接受的使用从另一个模块导入的功能,所以它与你的特定实现的问题。没有一些演示代码,我们不能说这是什么。如果你想要返回值,队列可能是一个不错的选择。考虑'multiprocessing.pool.ThreadPool'其中大部分工作的为您服务。 – tdelaney
@phihag和tdelaney,问题是我的工作者函数是一个单独的文件中的类的方法,我没有提到静态方法的关键。现在我提到了工作者功能的静态方法,每一件事情都是可以的!你有什么想法吗?我在python线程方面还不是很熟练。 – Stateless