
正文
python线程函数调用 python中的线程
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
在Python 中,怎样让 worker 线程调用主线程的函数
# -*- coding: utf-8 -*-
import threading
import thread
import time
class Test(object):
def __init__(self):
# threading.Thread.__init__(self)
self._sName = "machao"
def process(self):
#args是关键字参数,需要加上名字,写成args=(self,)
th1 = threading.Thread(target=Test.buildList, args=(self,))
th1.start()
th1.join()
def buildList(self):
while True:
print "start"
time.sleep(3)
test = Test()
test.process()
相关问答
Q1: python怎么使同一个函数多线程调用两次
如果是同一包里面,直接就可以使用,如果不是同一个包,那么需要先import后,通过“包名.类名”才能使用。 下面是同一个包里面的案例: def a(): print(1) def b(): a() print (2) b()
Q2: python多线程怎样执行函数
将python线程函数调用你需要多线程并发执行的函数放入list中
import threading
threads = []
t1 = threading.Thread(target=函数名,args=参数)
threads.append(t1)
启动多线程
if __name__ == '__main__':
for t in threads:
t.setDaemon(True)
t.start()
t.join()
更多详细操作help(threading)
#coding=utf-8
import threading
from time import ctime,sleep
# 要启动的函数
def music(func):
for i in range(2):
print "I was listening to %s. %s" %(func,ctime())
sleep(1)
# 要启动的函数
def move(func):
for i in range(2):
print "I was at the %s! %s" %(func,ctime())
sleep(5)
threads = []
t1 = threading.Thread(target=music,args=(u'爱情买卖',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(u'阿凡达',))
threads.append(t2)
# 函数加入线程列表
if __name__ == '__main__':
for t in threads:
t.setDaemon(True)
t.start()
t.join() #子线程完成运行之前python线程函数调用,这个子线程的父线程将一直被阻塞python线程函数调用,不会退出
print "all over %s" %ctime()
Q3: Python 类中的方法如何多线程调用
# -*- coding: utf-8 -*-import threadingimport threadimport time class Test(object): def __init__(self): # threading.Thread.__init__(self) self._sName = "machao" def process(self): #args是关键字参数,需要加上名字,写成args=(self,) th1 = threading.Thread(target=Test.buildList, args=(self,)) th1.start() th1.join() def buildList(self): while True: print "start" time.sleep(3) test = Test()test.process()
Q4: 在C++中多线程调用python函数,有什么办法
以前在远标时也遇见过的确有多线程调用的冲突问题。 通常是初始化一个python解释器。作为全局变量。然后每个线程分别调用。
因为python解释器里有一个GIL的全局锁。所以要防止线程间因为GIL造成的死锁。
不过具体的使用方法,与单线程没有区别。初始化python解释器。然后加载脚本,运行,取得返回变量就可以了。
如果你使用system,就当我没有说。 即使是使用system,也会有多线程的冲突可能性。因为操作系统的管道管理,相关文件,相关数据库,临时文件等都可能会产生冲突。
Q5: python如何定义和调用函数
1、函数定义
①使用def关键字定义函数
②
def 函数名(参数1.参数2.参数3...):
"""文档字符串python线程函数调用,docstringpython线程函数调用,用来说明函数的作用"""
#函数体
return 表达式
注释的作用python线程函数调用:说明函数是做什么的,函数有什么功能。
③遇到冒号要缩进,冒号后面所有的缩进的代码块构成python线程函数调用了函数体,描述python线程函数调用了函数是做什么的,即函数的功能是什么。Python函数的本质与数学中的函数的本质是一致的。
2、函数调用
①函数必须先定义,才能调用,否则会报错。
②无参数时函数的调用:函数名(),有参数时函数的调用:函数名(参数1.参数2.……)
③不要在定义函数的时候在函数体里面调用本身,否则会出不来,陷入循环调用。
④函数需要调用函数体才会被执行,单纯的只是定义函数是不会被执行的。
⑤Debug工具中Step into进入到调用的函数里,Step Into My Code进入到调用的模块里函数。
关于python线程函数调用和python中的线程的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。






