您的位置:首页 > 编程语言 > Python开发

So cute are you Python 9

2013-10-18 21:07 489 查看
1.线程的简单使用

#!/usr/bin/evn puthon
#coding:utf-8
#FileName:Rlock.py
#Function: Show how to using threading with python
#History:17-10-2013
import threading
mylock = threading.RLock()
num= 0

class myThread(threading.Thread):
def __init__(self,name):
threading.Thread.__init__(self)
self.t_name=name

def run(self):
global num
while True:
mylock.acquire()
print '\nThread(%s) lovked,Number:%d'%(self.t_name,num)
if num>= 4:
mylockrelease()
print '\nThread(%s) released,Number:%d'%(self.t_name,num)
break

num+ 1
print '\nThread(%s) released,Number:%d'%(self.t_name,num)
mylock.release()
def test():
thread1 = myThread('A')
thread2 =myThread('B')
thread1.start()
thread2.start()

if __name__=='__main__':
test()

2.使用function 调用thread

#!/usr/bin/evn python
#coding:utf-8
#fileName:thread_a.py
#function:show how to use an thread.
#History:18-10-2013
import string,threading,time
def thread_main(a):
global count,mutex
#获得线程名
threadname = threading.currentThread().getName()
for x in xrange( 0,int(a)):
#取得锁
mutex.acquire()
count=count+ 1
#释放锁
mutex.release()
print'Thread name:-%s,out_count=%d,count=%d' %(threadname,x,count)
time.sleep( 1)
def main(num):
global count,mutex
threads =[]

count = 1
#创建一个锁
mutex=threading.Lock()
#创建一个线程对象
for x in xrange( 0,num):
threads.append(threading.Thread(target=thread_main,args=(10,)))
#启动所有线程
for t in threads:
t.start()
#主线程等待所有子线程退出
for t in threads:
t.join()

if __name__ == '__main__':
num= 4
#创建4个线程
main(num)

3.使用 线程类

#!/usr/bin/evn python
#coding:utf-8
#fileName:thread_a.py
#function:show how to use an thread ,with thread class
#History:18-10-2013
import threading
import time
class test(threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self)
self.__run__num=num

def run(self):
global count,mutex
threadname=threading.currentThread().getName()

for x in xrange( 0,int(self.__run__num)):
mutex.acquire()
count=count+ 1
mutex.release()
print 'ThreadName:_%s,out_loop=%d,count_:%d'%(threadname,x,count)

if __name__=='__main__':
global count,mutex
threads=[]
num= 4
count= 1
#创建锁
mutex =threading.Lock()
#创建对象
for x in xrange( 0,num):
threads.append(test(10))
#启动线程
for t in threads:
t.start()
#等待子线程结束
for t in threads:
t.join()


总结:我们会发现使用线程类时我们的线程要简洁一些。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: