python 使用multiprocessing需要注意的問題,pythonprocessing
我們在編寫程式的時候經常喜歡這樣寫代碼
import MySQLdbimport timefrom multiprocessing import Processconn = MySQLdb.connect('localhost', 'vearne', 'xx', 'test')def f(name): for i in xrange(10): cursor = conn.cursor() sql = "insert into car(name) values(%s)" param = [(name)] print param #time.sleep(1) n = cursor.execute(sql,param) cursor.close() conn.commit()if __name__ == '__main__': for i in xrange(10): p = Process(target=f, args=('bob',)) p.start()
上面的程式有問題嗎?
以上的程式在單進程的情況下,應該是沒有問題,但是在多進程的情況下,它是有錯誤的。
首先看看下面的源碼
class Process(object): ''' Process objects represent activity that is run in a separate process The class is analagous to `threading.Thread` ''' _Popen = None def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): assert group is None, 'group argument must be None for now' count = _current_process._counter.next() self._identity = _current_process._identity + (count,) self._authkey = _current_process._authkey self._daemonic = _current_process._daemonic self._tempdir = _current_process._tempdir self._parent_pid = os.getpid() self._popen = None self._target = target self._args = tuple(args) self._kwargs = dict(kwargs) self._name = name or type(self).__name__ + '-' + \ ':'.join(str(i) for i in self._identity) def run(self): ''' Method to be run in sub-process; can be overridden in sub-class ''' if self._target: self._target(*self._args, **self._kwargs) def start(self): ''' Start child process ''' assert self._popen is None, 'cannot start a process twice' assert self._parent_pid == os.getpid(), \ 'can only start a process object created by current process' assert not _current_process._daemonic, \ 'daemonic processes are not allowed to have children' _cleanup() if self._Popen is not None: Popen = self._Popen else: from .forking import Popen self._popen = Popen(self) # -- 建立 Popen 對象 -- _current_process._children.add(self) # 省略部分代碼 ... ... def _bootstrap(self): # -- _bootstrap 函數 -- from . import util global _current_process try: self._children = set() self._counter = itertools.count(1) try: sys.stdin.close() sys.stdin = open(os.devnull) except (OSError, ValueError): pass _current_process = self util._finalizer_registry.clear() util._run_after_forkers() util.info('child process calling self.run()') try: self.run() # -- 調用run函數 -- exitcode = 0 finally: util._exit_function() except SystemExit, e: if not e.args: exitcode = 1 elif isinstance(e.args[0], int): exitcode = e.args[0] else: sys.stderr.write(str(e.args[0]) + '\n') sys.stderr.flush() exitcode = 0 if isinstance(e.args[0], str) else 1 except: exitcode = 1 import traceback sys.stderr.write('Process %s:\n' % self.name) sys.stderr.flush() traceback.print_exc() util.info('process exiting with exitcode %d' % exitcode) return exitcode
from .forking import Popen 定義
class Popen(object): def __init__(self, process_obj): sys.stdout.flush() sys.stderr.flush() self.returncode = None self.pid = os.fork() # -- fork子進程 -- # fork 函數調用一次,會在返回兩次,一次在父進程中返回,返回的pid 值大於0 # 一次在子進程中返回,返回的pid值 等於 0 if self.pid == 0: # pid值 等於 0 說明 以下代碼都是在子進程中執行的 if 'random' in sys.modules: import random random.seed() code = process_obj._bootstrap() # -- 調用_bootstrap函數 -- sys.stdout.flush() sys.stderr.flush() os._exit(code)
從代碼中我們可以看出,python 的multiprocessing 使用fork建立子進程,並在子進程中執行run函數
man fork
可以得到如下資訊
Fork() causes creation of a new process. The new process (child process) is an exact copy of the calling process (parent process) except for the following: o The child process has a unique process ID. o The child process has a different parent process ID (i.e., the process ID of the parent process). o The child process has its own copy of the parent's descriptors. These descriptors reference the same underlying objects, so that, for instance, file pointers in file objects are shared between the child and the parent, so that an lseek(2) on a descriptor in the child process can affect a subsequent read or write by the parent. This descriptor copying is also used by the shell to establish standard input and output for newly created processes as well as to set up pipes. o The child processes resource utilizations are set to 0; see setrlimit(2).
fork 函數建立的子進程是父進程的完全拷貝,他們擁有相同的檔案描述符。這樣如果在父進程中建立了串連,就會出現父進程和多個子進程公用一個串連,會出現無法預料的錯誤。
(每個串連都有獨立的讀緩衝區和寫緩衝區,多個進程的對讀緩衝區和寫緩衝區的操作會導致資料混亂)
所以我們應該在子進程中建立串連,這樣就能夠避免問題的發生。
import MySQLdbimport timefrom multiprocessing import Processclass SLWorker(Process): def __init__(self): super(SLWorker, self).__init__() self.conn = None def run(self): # *** 注意這裡 *** 串連消極式載入, 也就是說串連在子進程中被建立 if self.conn == None: self.conn = MySQLdb.connect('localhost', 'vearne', 'xxx', 'test') for i in xrange(10): cursor = self.conn.cursor() sql = "insert into car(name) values(%s)" name = "bob" param = [(name)] print param #time.sleep(30) n = cursor.execute(sql,param) cursor.close() self.conn.commit() def __del__(self): if self.conn != None: self.conn.close()if __name__ == '__main__': ll = [] for i in xrange(10): p = SLWorker() p.start() ll.append(p) for p in ll: p.join()
答案歸結為只需要將在子進程中建立串連,或者串連延遲建立就能夠解決這個問題
其實現在有很多串連池都是延遲建立串連,沒有仔細看,有研究的分享下。
PS: celery 和rq 也都會有這樣的問題,請大家引起足夠重視
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。