2010-11-21 152 views
2

如果我有10个查询,并且每个查询正在更新一个特定的表(即10个不同的表)。MySQL可以支持每个连接的并发查询吗?

我可以打开一个mySQL连接,产生10个线程,每个线程处理1个查询,以便它们可以并发运行而不是逐个执行。

谢谢!

回答

5

,你不行:

MySQL客户端库(至少本机C之一)不是线程安全的使用在不同的线程相同的连接。您需要使用每个线程的连接。

+0

如果你开始从同一线程多个异步查询? – 2013-06-19 17:47:21

0

由于MySQL协议的工作方式,如果您只打开一个连接,它们将逐个发送到服务器。

1

如果您只是需要并行运行更新/插入查询(根据MySQL API异步) - 您可以使用INSERT DELAYED和UPDATE LOW_PRIORITY查询。

0

没有文件“log.conn.txt”创建的,所以在单一MySQL客户端连接的并发查询之间没有冲突:

<? 
declare(ticks=1); 
pcntl_signal(SIGUSR1, create_function('$signo', 'sleep(1);while (($pid=pcntl_wait(@$status, WNOHANG))>0) {}'));//protect against zombie children 
$pdo=new PDO('mysql:host=192.168.0.2;port=3306;dbname=baseinfo', 'dev', 'dev', 
      array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION, 
        PDO::MYSQL_ATTR_INIT_COMMAND=>'set names utf8' 
       ) 
      ); 
for ($i=0; $i<20; ++$i) 
    {if (($pid=pcntl_fork())===-1) 
     {//... 
     continue; 
     } 
    else if ($pid) 
      {$pids[]=$pid; 
      pcntl_wait($status, WNOHANG); //protect against zombie children, one wait vs one child 
      } 
    else if ($pid===0) 
      {ob_start();//prevent output to main process 
      register_shutdown_function(create_function('$pars', 'ob_end_clean();posix_kill(posix_getppid(), SIGUSR1);posix_kill(getmypid(), SIGKILL);'), array());//to kill self before exit();, or else the resource shared with parent will be closed 
      for ($j=0; $j<200; ++$j) 
       {try 
        {file_put_contents('log.'.$i.'.txt', $pdo->query('select partner_login from base_account where id=100')->fetch(PDO::FETCH_COLUMN, 0)."\t".time().substr(microtime(),2,6)."\n", FILE_APPEND); 
        } 
       catch (Exception $e) 
         {if ($pdo->getAttribute(PDO::ATTR_SERVER_INFO)==='MySQL server has gone away') 
          {file_put_contents('log.conn.txt', time().substr(microtime(),2,6).":{$i}:{$j} lost\n", FILE_APPEND); 
          $pdo=&new PDO('mysql:host=192.168.0.2;port=3306;dbname=baseinfo', 'dev', 'dev', 
             array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION, 
               PDO::MYSQL_ATTR_INIT_COMMAND=>'set names utf8' 
              ) 
             ); 
          } 
         } 
       usleep(50000); 
       } 
      exit();//avoid foreach loop in child process 
      } 
    } 
//wait all child to end, avoid close db connection before all children self killed 
foreach ($pids as $p) 
     {pcntl_waitpid($p, $status); 
     } 
?> 
+0

遗憾的是,有时,2或3个子进程在与mysql lib客户端通信时被阻塞,并且这些子进程永远不会结束,“PDO :: ATTR_TIMEOUT”将不能解决问题 – diyism 2012-03-13 06:09:34