python
threading
多线程
一. Threading简介
首先看下面的没有用Threading的程序
- ):
- s += i
- time.sleep(
- ):
- s += i
- time.sleep()]
- ):
- print()
- ):
- print(
- threading:
- threading:
- 主线程等待t这个线程
- threading:
- Main:
- threading:
- Main:
- threading:
- Main:
- threading:
- Main:
- threading:
- Main:
- threading:
- Main:
- threading:
- Main:
- Main:
- Main:
- [Finished )
- print()
- print(
- lock = threading.Lock() ):
- lock.acquire()
- print(share)
- share += self.i
- time.sleep(random.random())
- print()
- tt = MyThread()
- t.start()
- tt.start()
- >>>
- + =
- + =
- + =
- + =
- [Finished ):
- + =
- + =
- + =
- + =
- [Finished
- share_cond = threading.Condition()
- print(self.name,share)
- share_cond.notify() )
- )
- Custom
- Produce
- Custom
- Produce
- Custom
- ...
- ...
- ...
上面的结果会一直重复执行下去
3 ) 信号量threading.Semaphore
属性
实例化时,指定使用量。
其内置计数器,锁定时+1,
释放时-1,计数器为0则阻塞。acquire(blocking=True,timeout=None)
release()释放锁。
- )
- )
- sema.release()
- print(self.name,)]
- Sema Had got resource.
- Sema Had got resource.
- Sema Had got resource.
- Sema Had released resource.
- Sema Had got resource.
- Sema Had released resource.
- Sema Had released resource.
- Sema Had got resource.
- Sema Had released resource.
- Sema Had released resource.
- [Finished )
- print('Main thread set event flag!')
- event.set()
- if __name__ == '__main__':
- thw = MyThreadWait()
- thm = MyThreadMain()
- thw.start()
- thm.start()
- >>>
- Wait Thread Wait...
- Main thread set event flag!
- Wait Thread Start...
- [Finished in 3.6s]
好了,大概就是这些了,其他的以后再补充,另外感谢麦子学院提供的免费课程~~~真心不是打广告
为了避嫌,顺便感谢一下imooc,极客学院~很多都是从这些造福人类的网站学到的。
另附上麦子学院的视频教程,毕竟要学会感恩嘛
http://www.maiziedu.com/course/644-9663/
marsggbo笔记出品,必属精品