初学多线程
想实现每秒执行一程序。因为怕要执行的耗时过长,影响计时器,所以用多线程。
import time
import threading
class Intervalfunc(threading.Thread): #
def __init__(self,args):
self.dur=args
threading.Thread.__init__(self)
def run(self):
apply(self.dosth)
def __del__(self):
print self,'deleted'
print time.clock()-self.st
def dosth(self):
self.st=time.clock()
while 1:
time.sleep(self.dur)
Myfunc().start()
class Myfunc(threading.Thread):
def __init__(self,e=''):
threading.Thread.__init__(self)
def run(self):
apply(self.dosth)
def __del__(self):
print self,'deleted'
def dosth(self):
print "do sth"
Intervalfunc(1).start()
这样写没什么问题,不过貌似要不停的创建删除threading。我想让就建2个,保持运行:
import threading
import time
class mythread(threading.Thread):
def __init__(self,args):
self.dur=args
self.go=0
threading.Thread.__init__(self)
def run(self):
apply(self.dosth)
def __del__(self):
print self,'deleted'
print time.clock()-self.st
def dosth(self):
global te
global count
self.st=time.clock()
while 1:
lock.acquire()
if(te==0):
te=1
lock.release()
#print time.clock()-self.st
count+=1
elif(te==-1):
del self
break
else:
lock.release()
class Intervalfunc(threading.Thread):
def __init__(self,args):
self.dur=args
threading.Thread.__init__(self)
def run(self):
apply(self.dosth)
def __del__(self):
global count
print count
print self,'deleted'
print time.clock()-self.st
def dosth(self):
global te
self.st=time.clock()
while 1:
lock.acquire()
time.sleep(self.dur)
te=0
lock.release()
time.sleep(self.dur)
if(time.clock()-self.st)>50:
te=-1
break
te=0
count=0
lock=threading.Semaphore()
mythread(0).start()
Intervalfunc(0.5).start()
cpu占有率巨高,执行3600秒,实际运行的次数会丢失。本人初学多线程希望达人能解释一二
线程的如何让期休眠?