2010-11-21 148 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