zoukankan      html  css  js  c++  java
  • python进阶笔记 thread 和 threading模块学习

    Python通过两个标准库thread和threading提供对线程的支持。
    thread提供了低级别的、原始的线程以及一个简单的锁。
    threading基于Java的线程模型设计。
    锁(Lock)和条件变量(Condition)在Java中是对象的基本行为(每一个对象都自带了锁和条件变量),而在Python中则是独立的对象。
    start_new_thread()要求一定要有前两个参数。所以,就算我们想要运行的函数不要参数,我们也要传一个空的元组。

    test_thread.py
    #! /usr/bin/env python
    # -*- coding:utf-8 -*-
    import thread
    import time
    from time import sleep,ctime

    test_list = [5,8]
    def f1():
    print 'start f1 at:',ctime()
    sleep(5)
    print 'f1 done at:',ctime()
    def f2():
    print 'start f1 at:',ctime()
    sleep(3)
    print 'f1 done at:',ctime()
    def main():
    print "start:",ctime()
    thread.start_new_thread(f1,())
    thread.start_new_thread(f2,())
    sleep(6)
    print "all end:",ctime()
    if __name__ == '__main__':
    main()

    test_threading.py
    #! /usr/bin/env python
    # -*- coding:utf-8 -*-
    import threading
    import time

    exitFlag = 0

    class myThread(threading.Thread):
    def __init__(self,threadID,name,delay):
    threading.Thread.__init__(self)
    self.threadID = threadID
    self.name = name
    self.delay = delay
    def run(self):
    print "Starting" + self.name
    print_time(self.name,self.delay,5)
    print "Exiting" + self.name
    def print_time(threadName,delay,counter):
    while counter:
    try:
    if exitFlag:
    thread.exit()
    time.sleep(delay)
    print "%s:%s" % (threadName, time.ctime(time.time()))
    counter -= 1
    except Exception,e:
    logging.info(e)
    thread1 = myThread(1,"Thread-1",1)
    thread2 = myThread(2,"Thread-2",2)

    thread1.start()
    thread2.start()

    print "Exiting Main Thread"

    python多线程threading.Lock锁的用法

    #创建锁
    mutex = threading.Lock()
    #锁定
    mutex.acquire([timeout])
    #释放
    mutex.release()

    test_threading_lock.py
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-

    import threading
    import time

    class my_thread(threading.Thread):
    def run(self):
    global num
    time.sleep(1)
    if mutex.acquire(1):
    num = num + 1
    msg =self.name + 'set num to '+str(num)
    print msg
    mutex.release()
    num = 0
    mutex = threading.Lock()
    def test():
    for i in range(5):
    t = my_thread()
    t.start()
    if __name__ == '__main__':
    test()

    python 多线程中常用到的几个方法,链接地址:http://blog.chinaunix.net/uid-27571599-id-3484048.html



     
  • 相关阅读:
    助你成功:十四个可以运用在任何领域的心理定律
    人生没有“如果…”,二十条经典领悟切莫错过!
    “潜意识”下的奇迹:成功说服的七条法则
    成就你一生的100句名言,改变从今天开始~
    命好不如习惯好!改造我们的习惯领域
    成功从现在开始:改变你一生的七句话
    职业经理人必须牢记六字原则:新、信、行、馨、型、星
    不要害怕自己与众不同:十个成功的秘诀
    价值百万:八个心态和十三个习惯成就成功者!
    代长珍(帮别人名字作诗)
  • 原文地址:https://www.cnblogs.com/forward-wang/p/5970640.html
Copyright © 2011-2022 走看看