多线程

多线程

1、低级API使用

#-*-coding:utf-8-*-

import thread
import time

#函数
def sayhello(name,age):
    print "%s,%d"%(name,age)

#try - catch
try:
    thread.start_new_thread(sayhello, ("tom", 12))
except Exception as e:
    print e


#死循环
while(True):
    time.sleep(1)

2、高级API

#使用高级threading类
import threading

#定义玩家线程类
class Play(threading.Thread):
    def run(self):
        print "%s 出发了!!!"%(self.name)
        time.sleep(self.sleep)
        print "%s 到了!!!"%(self.name)

    def __init__(self , name , sleep):
        threading.Thread.__init__(self)
        self.name = name
        self.sleep = sleep

#创建4个玩家
p1 = Play("tom1" ,8)
p2 = Play("tom2" ,3)
p3 = Play("tom3" ,2)
p4 = Play("tom4" ,5)

p1.start()
p2.start()
p3.start()
p4.start()

p1.join()
p2.join()
p3.join()
p4.join()

print "开局!!!"

3、线程安全问题

售票问题是经典的多线程安全问题,python支持同步机制,使用lock对象进行上锁,获得锁的方式是threading.lock()方法。

# -*-coding:utf-8-*-

import thread
import threading
import time

#总票数
tickets = 100

#买票方法
#获得锁对象
lock = threading.Lock()
def getTick():
    global tickets
    tick = tickets
    #上锁
    lock.acquire()
    tickets -= 1
    #解锁
    lock.release()
    if (tick < 1):
        return -1
    return tick

# 定义玩家线程类
class Saler(threading.Thread):
    def run(self):
        while(True):
            t = getTick()
            if(t == -1):
                return ;
            print "%s : %d"%(self.name , t)

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

s1 = Saler("s1")
s2 = Saler("s2")
s1.start()
s2.start()

while(True) :
    time.sleep(1)
原文地址:https://www.cnblogs.com/xupccc/p/9543935.html