thread/threading

thread/threading

thread

  • 简单的线程

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

threading

  • threading通过对thread模块进行二次封装,提供了更方便的API来操作线程

1. EXP1, threading 通过Threading.Thread构造线程

 
 
  1. # encoding: UTF-8
  2. # author:sxq
  3. import threading,time,random
  4. # 方法1:将要执行的方法作为参数传给Threading.Thread的构造方法
  5. count = 0
  6. lock = threading.Lock()
  7. def func():
  8. global count
  9. global lock
  10. lock.acquire()
  11. print 'func() passed to Thread'
  12. for i in xrange(10000):
  13. #print count
  14. count += 1
  15. lock.release()
  16. for i in range(5):
  17. t = threading.Thread(target = func, args = (), name = 'thread-' + str(i)).start()
  18. print count
  19. time.sleep(3)
  20. print count
  21. print type(t)

2. EXP2, threading 通过从 Thread 继承,并重写 run() 构造线程

 
 
  1. # encoding: UTF-8
  2. # author:sxq
  3. import threading,time,random
  4. # 方法2:从Thread继承,并重写run()
  5. count = 0
  6. lock = threading.Lock()
  7. class MyThread(threading.Thread):
  8. def run(self):
  9. global count
  10. global lock
  11. print 'pass'
  12. lock.acquire()
  13. for i in xrange(10000):
  14. count += 1
  15. lock.release()
  16. for i in range(5):
  17. MyThread().start()
  18. time.sleep(3)
  19. print count




转载于:https://www.cnblogs.com/lshconfigure/p/5775262.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值