python之线程

什么是线程?

开启线程的两种方式

方式一:

 1 import time
 2 import random
 3 from threading import Thread
 4 
 5 
 6 def eat(name):
 7     print('{} is eating'.format(name))
 8     time.sleep(random.randrange(1, 5))
 9     print('{} has gone'.format(name))
10 
11 
12 if __name__ == "__main__":
13     t1 = Thread(target=eat, args=('james', ))
14     t1.start()
15     print('\n主线程')

方式二:

 1 import time
 2 import random
 3 from threading import Thread
 4 
 5 
 6 class MyThread(Thread):
 7     def __init__(self, name):
 8         super().__init__()
 9         self.name = name
10 
11     def run(self):
12         print('{} is eating'.format(self.name))
13         time.sleep(random.randrange(1, 5))
14         print('{} has gone'.format(self.name))
15 
16 
17 if __name__ == "__main__":
18     t1 = MyThread('james')
19     t1.start()
20     print('\n主线程')

进程与线程之间的区别

  • 开进程的开销远大于开线程
  • 同一进程内的多个线程共享进程的地址空间
  • 同一个进程下的线程的pid是一样的

线程的常见属性和方法

获取线程名称

 1 import time
 2 import random
 3 from threading import Thread, current_thread
 4 from multiprocessing import Process, current_process
 5 
 6 
 7 class MyThread(Thread):
 8     def __init__(self, name):
 9         super().__init__()
10         self.name = name
11 
12     def run(self):
13         print('{} is eating'.format(self.name))
14         time.sleep(random.randrange(1, 5))
15         print(current_thread().getName())
16         print('{} has gone'.format(self.name))
17 
18 
19 if __name__ == "__main__":
20     t1 = MyThread('james')
21     t1.start()
22     print('\n主线程', current_thread().getName())

 

 互斥锁

 1 from threading import Thread, Lock
 2 import time
 3 
 4 n = 100
 5 
 6 def task():
 7     global n
 8     mutex.acquire()
 9     temp = n
10     time.sleep(0.1)
11     n = temp - 1
12     mutex.release()
13 
14 
15 if __name__ == "__main__":
16     mutex = Lock()
17     t_l = []
18     for i in range(100):
19         t = Thread(target=task)
20         t_l.append(t)
21         t.start()
22 
23     for t in t_l:
24         t.join()
25 
26     print('', n)

将并发的过程变为串行的过程

posted @ 2020-11-13 10:53  蟹老板bb  阅读(109)  评论(0编辑  收藏  举报