1. Thread Mode code
#!/usr/bin/python#_*_coding:utf-8_*_import threadingimport timedef producer (): print ' chef : and other people to buy steamed buns ... ' event.wait () event.clear () print ' Sb is coning for baozi ' print ' chef : making  A BAOZI FOR SB ... ' time.sleep (3) print ' chef : your buns are ready ' event.set () Def consumer (): print ' maxi : to buy steamed buns ' event.set () time.sleep (1) print ' Maxi : waiting for baozi tobe readly ' event.wait () print ' Gee, it's delicious ' event = threading. Event () p = threading. Thread (Target=producer) c = threading. Thread (Target=consumeR) P.start () C.start ()
Operation Result:
650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M00/89/7B/wKiom1gUtqmACP2oAABMPoStUdw141.png-wh_500x0-wm_3 -wmp_4-s_4076459701.png "title=" Qq20161029224807.png "alt=" Wkiom1gutqmacp2oaabmpostudw141.png-wh_50 "/>
2, how to call their own thread class
The code is as follows:
#!/usr/bin/python#_*_coding:utf-8_*_from Threading Import Threadimport timeclass MyThread (Thread): #调用我自己的线程方法前, The run () method of the parent class must be called first; def run: print ' MyThread ' #Thread. Run (self) #启用父类的run (), so that you can call your own thread function super (MyThread. R). Un () def Bar (): print ' bar ', T1 = MyThread (target = Bar) #我的线程方法Bar () function; T1.start () print ' over '
Operation Result:
650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M02/89/7B/wKiom1gUuKDRrmH0AAAjRKUvsbg297.png-wh_500x0-wm_3 -wmp_4-s_2938423919.png "title=" Qq20161029225631.png "alt=" Wkiom1guukdrrmh0aaajrkuvsbg297.png-wh_50 "/>
3. Thread Safety
The code is as follows:
#!/usr/bin/python#_*_coding:utf-8_*_import Threadingimport timenum = 0 def run (n): Time.sleep (1) samp.acquire () #锁 on global num num + = 1 print '%d\n '% num samp.release () #释放锁 #lock = Threading. Lock () #锁机制, Samp = Threading. Boundedsemaphore (4) #信号量for I in range (£): T = Threading. Thread (target = run, args = (i,)) T.start ()
Because it gives 4 semaphores, it is possible to seize resources at the same time up to 4 processes;
Operation Result:
650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M01/89/80/wKioL1gV1c_Su7gFAAAruRTW6Gw204.png-wh_500x0-wm_3 -wmp_4-s_3159204094.png "title=" Qq20161030191309.png "alt=" Wkiol1gv1c_su7gfaaarurtw6gw204.png-wh_50 "/>
When we change the semaphore to 1 o'clock, it is equivalent to the monopoly, at which point the result is definitely 1000;
650) this.width=650; "Src=" Http://s2.51cto.com/wyfs02/M01/89/82/wKiom1gV1mOy3H0uAAAkWqqqgcE402.png-wh_500x0-wm_3 -wmp_4-s_2536936267.png "title=" Qq20161030191517.png "alt=" Wkiom1gv1moy3h0uaaakwqqqgce402.png-wh_50 "/>
This article is from the "11586096" blog, please be sure to keep this source http://11596096.blog.51cto.com/11586096/1867424
Python Threading Programming