当我的目标函数在另一个 .py 文件中时,在 Python 中使用多线程 API
Using multithreading API in Python when my target function in another .py file
我将在我的 Python 应用程序中使用线程。假设我想在 main.py 文件中使用以下代码在线程中 运行 worker() 函数:
def threadcalling():
t = threading.Thread(target=worker())
threads.append(t)
t.start()
我在 work.py 文件中的 worker 函数是这样的:
def worker():
"""thread worker function"""
print 'Worker'
return
我的问题:如果 worker() 函数在我调用的同一个 .py 文件中,一切正常,但是如果 worker() 函数在我导入的另一个 .py 文件中在我使用 import 命令的主脚本中,出现了这个错误:
<type 'exceptions.ValueError'>
对我来说,这有效:
dede@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()
dede@i5:~>猫cc.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def worker():
"""thread worker function"""
print 'Worker'
return
dede@i5:~> python bb.py
Worker
要从您的 worker() 返回值,请使用全局变量(带锁)或队列。
我将在我的 Python 应用程序中使用线程。假设我想在 main.py 文件中使用以下代码在线程中 运行 worker() 函数:
def threadcalling():
t = threading.Thread(target=worker())
threads.append(t)
t.start()
我在 work.py 文件中的 worker 函数是这样的:
def worker():
"""thread worker function"""
print 'Worker'
return
我的问题:如果 worker() 函数在我调用的同一个 .py 文件中,一切正常,但是如果 worker() 函数在我导入的另一个 .py 文件中在我使用 import 命令的主脚本中,出现了这个错误:
<type 'exceptions.ValueError'>
对我来说,这有效:
dede@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()
dede@i5:~>猫cc.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def worker():
"""thread worker function"""
print 'Worker'
return
dede@i5:~> python bb.py
Worker
要从您的 worker() 返回值,请使用全局变量(带锁)或队列。