import os
print('Process (%s) start...' % os.getpid())
pid = os.fork()
if pid == 0 :
print('I an child process (%s) and my parent is %s' % (os.getpid(), os.getpid()))
else :
print('I (%s) just created a child process (%s).' % (os.getpid(), pid))
'''
multiprocessing
'''
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.' )
'''
Pool
如果需要启动大量子进程,可以用进程池的方式批量创建子进程
'''
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('Wating 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)
'''
进程间通信
'''
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__' :
q = Queue()
pw = Process(target=write, args= (q,))
pr = Process(target=read, args= (q,))
pw.start()
pr.start()
pw.join()
pr.terminate()
'''
多线程
多任务可以有多个进程完成, 也可以由一个进程内的多线程完成
'''
import time, threading
print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>以下是多线程执行代码' )
def loop () :
print('thread %s is runing...' % threading.current_thread().name)
n = 0
while n < 5 :
n = n + 1
print('thread %s >>> %s' % (threading.current_thread().name, n))
time.sleep(1 )
print('thread %s ended.' % threading.current_thread().name)
print('thread %s is runing...' % threading.current_thread().name)
t = threading.Thread(target=loop, name='LoopThread' )
t.start()
t.join()
print('thread %s ended.' % threading.current_thread().name)
'''
Lock
多线程和多进程最大的不同在于,多进程中,同一个变量各自有一份拷贝存在于每个进程中,互不影响,
而多线程中,所有变量都由所有线程共享,所有,任何一个变量都可以被任何一个线程修改,
因此,线程之间共享数据最大危险在于多个线程同时修改一个变量
'''
blance = 0
lock = threading.Lock()
def run_thread (n) :
for i in range(100000 ):
lock.acquire()
try :
pass
finally :
pass
更多精彩内容访问个人站点www.gaocaishun.cn