Python线程

本文主要介绍python线程相关知识。

1.开启线程

  • 利用threading.Thread()类实例化

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    from threading import Thread
    import time
    def sayhi(name):
    time.sleep(2)
    print('%s say hello' %name)

    if __name__ == '__main__':
    t=Thread(target=sayhi,args=('egon',))
    t.start()

    print('主线程')
  • 通过继承Thread类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    from threading import Thread
    import time

    class Sayhi(Thread):
    def __init__(self,name):
    super().__init__()
    self.name = name
    def run(self):
    time.sleep(2)
    print("%s say hello" %self.name)

    if __name__ == "__main__":
    t = Sayhi("egon")
    t.start()
    print("主线程")

join和setDaemon

1
2
3
4
5
6
7
8
9
10
11
12
13
from threading import Thread
import time
def sayhi(name):
time.sleep(2)
print('%s say hello' %name)

if __name__ == '__main__':
t=Thread(target=sayhi,args=('egon',))
t.setDaemon(True) #设置为守护线程,主线程结束,子线程也跟着线束。
t.start()
t.join() #主线程等待子线程运行结束
print('主线程')
print(t.is_alive())

2.锁机制

  • 同步锁

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    import time
    import threading

    num = 100 #设定一个共享变量
    def addNum():
    with lock:
    global num
    temp = num
    time.sleep(0.1)
    num = temp-1 #对此公共变量进行-1操作

    thread_list = []

    if __name__ == '__main__':
    lock = threading.Lock() #由于同一个进程内的线程共享此进程的资源,所以不需要给每个线程传这把锁就可以直接用。
    for i in range(100):
    t = threading.Thread(target=addNum)
    t.start()
    thread_list.append(t)

    for t in thread_list: #等待所有线程执行完毕
    t.join()
    print("result: ",num)
  • 死锁与递归锁
    所谓死锁:是指两个或两个以上的进程或线程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态,或系统产生了死锁。这此永远在互相等待的进程称死锁进程。
    锁提供如下方法:
    (1)Lock.acquire([blocking])
    (2)Lock.release()
    (3)threading.Lock() 加载线程的锁对象,是一个基本的锁对象,一次只能一个锁定,其余锁请求,需等待锁释放后才能获取
    (4)threading.RLock() 多重锁,在同一线程中可用被多次acquire。如果使用RLock,那么acquire和release必须成对出现,
    调用了n次acquire锁请求,则必须调用n次的release才能在线程中释放锁对象

无锁:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#coding=utf8
import threading
import time

num = 0

def sum_num(i):
global num
time.sleep(1)
num +=i
print num

print '%s thread start!'%(time.ctime())

try:
for i in range(6):
t =threading.Thread(target=sum_num,args=(i,))
t.start()

except KeyboardInterrupt,e:
print "you stop the threading"

print '%s thread end!'%(time.ctime())

引入锁:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#coding=utf8
import threading
import time

num = 0

def sum_num(i):
lock.acquire()
global num
time.sleep(1)
num +=i
print num
lock.release()

print '%s thread start!'%(time.ctime())

try:
lock=threading.Lock()
list = []
for i in range(6):
t =threading.Thread(target=sum_num,args=(i,))
list.append(t)
t.start()

for threadinglist in list:
threadinglist.join()

except KeyboardInterrupt,e:
print "you stop the threading"

print '%s thread end!'%(time.ctime())

---------------- The End ----------------