-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProcesses and threads.py
105 lines (82 loc) · 2.73 KB
/
Processes and threads.py
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
from multiprocessing import Process
import os
# def run_proc(name):
# print('Run child process %s (%s)...' % (name, os.getpid()))
# if __name__=='__main__':
# print('Parent process %s.' % os.getpid())
# p = Process(target=run_proc, args=('test',))
# print('Child process will start.')
# p.start()
# p.join()
# print('Child process end')
# from multiprocessing import Pool
# import os, time, random
#
# def long_time_task(name):
# print('Run task %s (%s)...' % (name, os.getpid()))
# start = time.time()
# time.sleep(random.random() * 3)
# end = time.time()
# print('Task %s runs %0.2f seconds.' % (name, (end - start)))
#
# if __name__=='__main__':
# print('Parent process %s.' % os.getpid())
# p = Pool(4)
# for i in range(5):
# p.apply_async(long_time_task, args=(i,))
# print('Waiting for all subprocesses done...')
# p.close()
# p.join()
# print('All subprocesses done.')
import subprocess
print('$ nslookup www.python.org')
r = subprocess.call(['nslookup', 'www.python.org'])
print('Exit code:', r)
# print('$ nslookup')
# p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# output, err = p.communicate(b'set q=mx\npython.org\nexit\n')
# print(output.decode('utf-8'))
# print('Exit code:', p.returncode)
from multiprocessing import Process, Queue
import os, time, random
# 写数据进程执行的代码
def write(q):
print('Process to write: %s' % os.getpid())
for value in ['A','B', 'C']:
print('Put %s to queue...' % value)
q.put(value)
time.sleep(random.random())
# 读数据进程执行的代码:
def read(q):
print('Process to read: %s' % os.getpid())
while True:
value = q.get(True)
print('Get %s from queue.' % value)
if __name__=='__main__':
# 父进程创建Queue,并传给各个子进程
q = Queue()
pw = Process(target=write, args=(q,))
pr = Process(target=read, args=(q,))
# 启动子进程pw,写入:
pw.start()
# 启动子进程pr,读取:
pr.start()
# 等待pw结束:
pw.join()
# pr进程里是死循环,无法等待其结束,只能强行终止:
pr.terminate()
import time, threading
# 新线程执行的代码:
def loop():
print('threat %s is running...' % threading.current_thread().name)
n = 0
while n < 5:
n = n + 1
print('threat %s >>> %s' % (threading.current_thread().name, n))
time.sleep(1)
print('threat %s ended.' % threading.current_thread().name)
print('threat %s is running...' % threading.current_thread().name)
t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join()
print('threat %s ended.' % threading.current_thread().name)