我们在编写程序的时候经常喜欢这样写代码
import MySQLdb import time from multiprocessing import Process conn = 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 ‘‘‘