首页 > 代码库 > python3 进程和线程

python3 进程和线程

进程和线程

  1. 进程:内存独立,线程共享同一进程的内存
  2. 进程是资源的集合,线程是执行单位
  3. 进程之间不能直接互相访问,同一进程中的程可以互相通信
  4. 创建新进程消耗系统资源,线程非常轻量,只保存线程运行时的必要数据,如上下文、程序堆栈信息
  5. 同一进程里的线程可以相互控制,父进程可以控制子进程
技术分享
 1 import threading
 2 import time
 3 
 4 def sayhi(num):
 5     print(num:,num)
 6     time.sleep(3)
 7 
 8 a = threading.Thread(target=sayhi,args=(1,))
 9 b = threading.Thread(target=sayhi,args=(2,))
10 now1 = time.time()
11 print(now1)
12 a.start()
13 b.start()
14 now2 = time.time()
15 print(now2)
16 print(threading.active_count()) 
17 # 包含主线程,总共3个
18 print(a.getName())
19 print(b.getName())
20 
21 class MyThread(threading.Thread):
22     def __init__(self,n):
23         threading.Thread.__init__(self)
24         self.n = n
25 
26         def run(self):
27             print(running on thread $s%self.n)
28             time.sleep(3)
29 now3 = time.time()
30 print(now3)
31 t1 = MyThread(1)
32 t2 = MyThread(2)
33 t1.start()
34 t2.start()
35 print(t1.getName())
36 print(t2.getName())
37 now4 = time.time()
38 print(now4)
39 
40 thread_list = []
41 for i in range(10):
42     s1 = threading.Thread(target=sayhi,args=(i,))
43     s1.start()
44     thread_list.append(s1)
45 now5 = time.time()
46 print(now5)
47 for r in thread_list:
48     r.join() # s1.wait()
49 print(--work done--)
50 now6 = time.time()
51 print(now6)
52 print(primary.center(20,-))
53 
54 
55 for ii in range(10):
56     s2 = threading.Thread(target=sayhi)
57     s2.setDaemon(s2)
58     s2.start()
View Code

 

python3 进程和线程