天地一扁舟 2015-02-28 15:45 采纳率: 0%
浏览 3187

python中如何对类的成员函数开启线程?

单独对某个函数开启线程是可以的,比如下面的代码:
import threading
import thread
import time
def doWaiting():
print 'start waiting:', time.strftime('%H:%M:%S')
time.sleep(3)
print 'stop waiting', time.strftime('%H:%M:%S')
thread1 = threading.Thread(target = doWaiting)
thread1.start()
time.sleep(1) #确保线程thread1已经启动
print 'start join'
thread1.join() #将一直堵塞,直到thread1运行结束。
print 'end join'

但是对类的成员函数开启线程,程序报错:
th1 = threading.Thread(target = Test.buildList , (self ,))
SyntaxError: non-keyword arg after keyword arg

程序如下:
import threading
import thread
import time
class Test(object):
def init(self):
#threading.Thread.__init__(self)
self._sName = "machao"

def process(self):
    th1 = threading.Thread(target = Test.buildList , (self ,)) 
    th1.start()
    th1.join()

def buildList(self):
    while True:
        print "start"
        time.sleep(3)

test = Test()
test.process()

  • 写回答

2条回答 默认 最新

  • oyljerry 2015-03-01 09:34
    关注

    target = self.buildList
    要用self而不是test

    评论

报告相同问题?

悬赏问题

  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效