python——多线程thread

python通过thread模块支持多线程,语法也很简洁,现在通过一个实例来看一下python中的多线程:

import thread
import time


#保证只额外启动一个线程
isRunning=False
#启动的时间控制,测试时间是23点44分,所以定的是这个时间,可以用于指定定时任务的执行时间
timer_hour=23
timer_min=44

#额外其他一个线程处理任务
def another_thread():
    print '[another_thread] is start...'
    #声明使用全局变量isRunning
    global isRunning
    #for循环模拟任务执行
    for i in range(3):
        time.sleep(1)
        print '[another_thread] time: %s ' % time.strftime('%Y-%m-%d %X',time.localtime())
        print '[another_thread] Is Running: %s' % isRunning
    #此处只是为了保证该任务一天只启动一次,一分不会超过60秒
    time.sleep(60)
    print '[another_thread] is end...'
    #该状态只是为了保证该任务不会重复启动,当然对于任务可以设置一个超时时间,到时不结束自动终结
    isRunning = False

if __name__ == '__main__':
    while True:
        now = time.localtime()
        print '[main_thread] time: %s' % time.strftime('%Y-%m-%d %X',now)
        print '[main_thread] Is Running: %s' % isRunning
        if now.tm_hour==timer_hour and now.tm_min==timer_min and not isRunning:
            #进入任务前即置为True状态,防止重复启动
            isRunning = True
            #python开启一个新的线程,从后面打印日志的情况可以知道,并不会影响主线程的运行
            thread.start_new_thread(another_thread,())
         
        time.sleep(1)

代码执行后如下:

C:\Users\Captain\Desktop>python task.py
[main_thread] time: 2013-07-31 23:44:56
[main_thread] Is Running: False
[another_thread] is start...
[main_thread] time: 2013-07-31 23:44:57[another_thread] time: 2013-07-31 23:44:57

[main_thread] Is Running: True[another_thread] Is Running: True

[main_thread] time: 2013-07-31 23:44:58[another_thread] time: 2013-07-31 23:44:58

[main_thread] Is Running: True[another_thread] Is Running: True

[main_thread] time: 2013-07-31 23:44:59[another_thread] time: 2013-07-31 23:44:59

[another_thread] Is Running: True[main_thread] Is Running: True

[main_thread] time: 2013-07-31 23:45:00
[main_thread] Is Running: True
[main_thread] time: 2013-07-31 23:45:01
[main_thread] Is Running: True
[main_thread] time: 2013-07-31 23:45:02

该实例很简单,可按照这个思路,应用于定时任务,心跳检测,守护进程等实际场景中


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值