免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2046 | 回复: 1
打印 上一主题 下一主题

初学多线程 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-07-13 20:20 |只看该作者 |倒序浏览
想实现每秒执行一程序。因为怕要执行的耗时过长,影响计时器,所以用多线程。
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秒,实际运行的次数会丢失。本人初学多线程希望达人能解释一二

线程的如何让期休眠?

论坛徽章:
0
2 [报告]
发表于 2006-07-14 09:02 |只看该作者
在while中加上sleep()的语句可以把执行分出一些来,在mythread中加上试试。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP