返回顶部

收藏

python线程同步

更多

下面的python代码演示线程锁的用法和线程同步

#!/usr/bin/python

import threading
import time

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print "Starting " + self.name
        # Get lock to synchronize threads
        threadLock.acquire()
        print_time(self.name, self.counter, 3)
        # Free lock to release next thread
        threadLock.release()

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print "%s: %s" % (threadName, time.ctime(time.time()))
        counter -= 1

threadLock = threading.Lock()
threads = []

# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads
thread1.start()
thread2.start()

# Add threads to thread list
threads.append(thread1)
threads.append(thread2)

# Wait for all threads to complete
for t in threads:
    t.join()
print "Exiting Main Thread"

输出结果python Starting Thread-1 Starting Thread-2 Thread-1: Thu Mar 21 09:11:28 2013 Thread-1: Thu Mar 21 09:11:29 2013 Thread-1: Thu Mar 21 09:11:30 2013 Thread-2: Thu Mar 21 09:11:32 2013 Thread-2: Thu Mar 21 09:11:34 2013 Thread-2: Thu Mar 21 09:11:36 2013 Exiting Main Thread

标签:python

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. 妙音 发表 2018-06-28 23:14:12 TypeError: Unicode-objects must be encoded before
  2. 妙音 发表 2018-06-28 23:26:44 如何判断类是类
  3. the5fire 发表 2018-06-27 23:29:33 不太好升级的Python 3.7
  4. 博主 发表 2018-04-25 03:46:29 使用Python批量将Word文档转换为PDF
  5. 博主 发表 2018-04-25 03:46:29 使用Python批量将Word文档转换为PDF
  6. 测试小兵尼 发表 2018-06-25 07:30:11 我的自学Python之路
  7. 妙音 发表 2018-06-23 23:29:58 pycharm回车符问题
  8. 99527 发表 2018-06-24 13:45:48 注意!Python中的10个常见安全漏洞及修复方法
  9. zhuangli 发表 2018-06-24 11:46:07 资深程序员用Python爬取了11万Java程序员!Java原来是这样的呢!
  10. 博主 发表 2018-06-21 14:54:45 技巧收集-M1806
  11. admin 发表 2018-06-21 02:30:19 Nginx模块在Python开发中的应用
  12. admin 发表 2018-06-21 02:30:19 Nginx模块在Python开发中的应用

发表评论