码迷,mamicode.com
首页 > 其他好文 > 详细

thread/threading

时间:2016-08-16 10:32:43      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

thread/threading

1. EXP1, thread简单调用

  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. import thread
  4. import time
  5. # 为线程定义一个函数
  6. def threadTest(threadName):
  7. print "%s" %(threadName)
  8. # 创建两个线程
  9. try:
  10. thread.start_new_thread( threadTest, ("Thread-1",) )
  11. time.sleep(0.3)
  12. thread.start_new_thread( threadTest, ("Thread-2",) )
  13. time.sleep(0.3)
  14. except:
  15. print "Error: unable to start thread"

2. EXP2, thread加入锁

  • 起10个进程;
  • 单线程独占资源;
  • 用锁来保证每个线程结束后再执行下一个进程;
  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. import thread, time, random
  4. count = 0
  5. lock = thread.allocate_lock() #创建一个琐对象
  6. def threadTest():
  7. global count, lock
  8. print lock.acquire() #获取琐
  9. for i in xrange(10000):
  10. count += 1
  11. print lock.release() #释放琐
  12. #print thread.exit ()
  13. for i in xrange(10):
  14. thread.start_new_thread(threadTest, ())
  15. time.sleep(0.3)
  16. print count




thread/threading

标签:

原文地址:http://www.cnblogs.com/lshconfigure/p/5775262.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!