码迷,mamicode.com
首页 > 编程语言 > 详细

(七)8-3多线程实例和线程锁

时间:2017-12-14 03:58:53      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:utf8   release   name   log   2.0   run   elf   art   get   

Python中提供threading模块来对多线程的操作
线程是引用程序中工作的最小单元
线程的实现有2种方式
1、讲要执行的方法作为参数传给Thread的构造方法
2、从Thread继承,重写run()

#!/usr/bin/env python 
#coding:utf8

import  threading
def worker(n):
    print "start wworker {0}".format(n)
    
class MyThread(threading.Thread):
    def __init__(self,args):
        super(MyThread,self).__init__()
        self.args = args
    def run(self):
        print "start MyThread{0}".format(self.args)
if __name__ == "__main__":
    for i in xrange(1,6):
        t1 = threading.Thread(target=worker,args=(i,))
        t1.start()
    t1.join()

    for x in xrange(6,11):
        t2 = MyThread(x)
        t2.start()

执行结果:

start worker 1
start worker 2
start worker 3
start worker 4
start worker 5
start MyThread6
start MyThread7
start MyThread8
start MyThread9
start MyThread10

线程锁通过threading.Lock创建,函数执行过程只有获得锁,执行完要释放所
with lock 或
lock.acquire()
lock.release()

import  threading
import  time

def worker(name,lock):
    with lock:
        print "start {0} time:{1}".format(name,time.time())
        time.sleep(5)
        print "end {0} time:{1}".format(name, time.time())

if __name__ == "__main__":
    lock = threading.Lock()
    t1 = threading.Thread(target=worker,args=("worker1",lock))
    t2 = threading.Thread(target=worker,args=("worker2",lock))
    t1.start()
    t2.start()
    print "main end ,time: {0}".format(time.time())
    print "main end"

运行结果:

start worker1 time:1512184912.0
main end ,time: 1512184912.0
end worker1 time:1512184917.0
start worker2 time:1512184917.0
end worker2 time:1512184922.0

 

(七)8-3多线程实例和线程锁

标签:utf8   release   name   log   2.0   run   elf   art   get   

原文地址:http://www.cnblogs.com/pythonlx/p/8035444.html

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