8-3多线程实例和线程锁

Posted zhan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了8-3多线程实例和线程锁相关的知识,希望对你有一定的参考价值。

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多线程实例和线程锁的主要内容,如果未能解决你的问题,请参考以下文章

Java多线程锁的知识实例讲解

day39——多线程实例多线程锁

多线程

3.多线程学习笔记之共享模型之管程

39. Python 多线程实例 多线程锁

3.多线程学习笔记之共享模型之管程