python多线程总结

来源:互联网 发布:离散数学 编程 编辑:程序博客网 时间:2024/04/30 09:29

Python 多线程入门基础

Setdaemon()方法设置守护线程:当父线程结束的时候子线程无论是否执行完都要结束!

# -*- coding: utf-8 -*-#setDaemon()方法。主线程A中,创建了子线程B,并且在主线程A中调用了B.setDaemon(),# 这个的意思是,把主线程A设置为守护线程,这时候,要是主线程A执行结束了,就不管子线# B是否完成,一并和主线程A退出.这就是setDaemon方法的含义,这基本和join是相反的。# 此外,还有个要特别注意的:必须在start() 方法调用之前设置,如果不设置为守护线程,# 程序会被无限挂起。注意推出和挂起不一样import threadingimport timeclass MyThread(threading.Thread):    def __init__(self, id):        threading.Thread.__init__(self)    def run(self):        time.sleep(5)        print "This is " + self.getName()if __name__ == "__main__":    t1 = MyThread(999)    t1.setDaemon(True)    #这里打印出"I am the father thread."就结束了。子线程连同父线程被一同关闭!    t1.start()    print "I am the father thread."

Join()用法

保证此线程执行完之后再去执行下一个线程或者主线程

# -*- coding: utf-8 -*-import threadingimport timeclass MyThread(threading.Thread):    def __init__(self, id):        threading.Thread.__init__(self)        self.id = id    def run(self):        x = 0        time.sleep(10)        print self.idif __name__ == "__main__":    t1 = MyThread(999)    t2 = MyThread(11)    t1.start()    t1.join()    t2.start()    t2.join()
         
  for i in range(5):        print i    # t1.join()   #如果没有join()  先打印 12345 再去打印我们所定义的线程t1   id                    #如果有join()就在主线程中等待子线程 t1 执行完毕之后在去继续执行主线程    # 方法:主线程A中,创建了子线程B,并且在主线程A中调用了B.join(),    # 那么,主线程A会在调用的地方等待,直到子线程B完成操作后,才可以接    # 着往下执行,那么在调用这个线程时可以使用被调用线程的join方法。

通过线程调用函数

t1 =threading.Thread(target=music,args=(u'爱情买卖',))

第一个是函数第二个是形参

自定义线程

使用threading创建线程    也就是说我们可以自定义run()这里的run和上面调用一个函数差不多!只不过更方便了一体化!

下面自定义线程类

#!/usr/bin/python

# -*-coding: UTF-8 -*-

import threading

import time

exitFlag =0

class myThread(threading.Thread): 

 #继承父类   threading.Thread

 

def __init__(self, threadID, name, counter):

#构造器

        threading.Thread.__init__(self)

#先构造父类

        self.threadID= threadID

        self.name= name

        self.counter= counter

def run(self):                  

#把要执行的代码写到run函数里面线程在创建后会直接运行run函数

#也就是说 start()方法后运行的是run方法

        print"Starting "+self.name

        print_time(self.name,self.counter,5)

        print"Exiting "+self.name

def print_time(threadName, delay, counter):

    while counter:

        if exitFlag:

            thread.exit()

        time.sleep(delay)

        print"%s: %s"%(threadName,time.ctime(time.time()))

        counter -=1

# 创建新线程

thread1 = myThread(1,"Thread-1",1)

thread2 = myThread(2,"Thread-2",2)

# 开启线程

thread1.start()

thread2.start()

print"Exiting Main Thread"

以上程序执行结果如下;

StartingThread-1

StartingThread-2

ExitingMainThread

Thread-1:ThuMar2109:10:032013

Thread-1:ThuMar2109:10:042013

Thread-2:ThuMar2109:10:042013

Thread-1:ThuMar2109:10:052013

Thread-1:ThuMar2109:10:062013

Thread-2:ThuMar2109:10:062013

Thread-1:ThuMar2109:10:072013

ExitingThread-1

Thread-2:ThuMar2109:10:082013

Thread-2:ThuMar2109:10:102013

Thread-2:ThuMar2109:10:122013

ExitingThread-2

Lock 锁的使用

 主要解决线程安全问题:即当多个线程使用统一资源的时候保证一个资源只被一个线程所使用!
# coding : uft-8
import threading,time
class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        globaln, lock
        time.sleep(1)
        if lock.acquire():         #该资源一次只可以被一个线程所使用,其
                            #
他线程要等其他线程使用完之后才可以使用该资源
           
print n ,self.name
            n += 1
           
lock.release()
if "__main__" == __name__:
    n = 1
   
ThreadList = []
    lock = threading.Lock()
    for i in range(1,10):
        t = MyThread()
        ThreadList.append(t)
    for t in ThreadList:
        t.start()
    for t in ThreadList:
        t.join()

 

注意这种用法,创建组或者批量创建线程!    批量进行start()和join()

注意 线程的名字如果没有子类重写的话 会按次序 Thread-1 Thread-2 。。。自动命名

关于global用法  global可以使得在函数内

•hehe=6

def f():

•    hehe=2

•    print(hehe)

•f()

•  print(hehe) 


•  上述输出是2和6,也即f函数中print使用的是“局部变量hehe”,而最后一个print语句使用的全局hehe。

•  那么我们会有疑问,如果我可能在函数使用某一变量后又对其进行修改(也即再赋值),怎么让函数里面使用的变量是模块层定义的那个全局变量而不是函数内部的局部变量呢?这时候global修饰符就派上用场了。

•
hehe=6

def f():

•    global hehe

•    print(hehe)

•    hehe=3

•f()

print(hehe) 



在用global修饰符声明hehe是全局变量的hehe后(注意,global语句不允许同时进行赋值如global hehe=3是不允许的),上述输出是6和3,得到了我们想要的效果。

补充!

threading.Condition

可以把Condiftion理解为一把高级的琐,它提供了比Lock,RLock更高级的功能,允许我们能够控制复杂的线程同步问题。threadiong.Condition在内部维护一个琐对象(默认是RLock),可以在创建Condigtion对象的时候把琐对象作为参数传入。Condition也提供了acquire,release方法,其含义与琐的acquire,release方法一致,其实它只是简单的调用内部琐对象的对应的方法而已。Condition还提供了如下方法(特别要注意:这些方法只有在占用琐(acquire)之后才能调用,否则将会报RuntimeError异常。):

Condition.wait([timeout]):

wait方法释放内部所占用的锁,同时线程被挂起,直至接收到通知被唤醒或超时(如果提供了timeout参数的话)。当线程被唤醒并重新占有琐的时候,程序才会继续执行下去。

Condition.notify():

唤醒一个挂起的线程(如果存在挂起的线程)。注意:notify()方法不会释放所占用的琐。

?

1

2

Condition.notify_all()

Condition.notifyAll()

 

1 0
原创粉丝点击