从多个线程写入同一个文件.同步?锁定?[Pthreads] [PHP]


Writing to the same file from multiple threads . Synchronization? locking ? [Pthreads] [ PHP]

关于pthreads多线程的基本问题…在不同/相似/相同时间写同一文件的线程数。我如何使它"安全"?例如,确保没有两个线程同时尝试写。

  class WebRequest extends Thread {
      public $cik;
      public function __construct($cik){
          $this->cik = $cik;
      }
      public function run() {
          for_cik($this->cik);
          echo 'Running Thread : ' . $this->getCurrentThreadId() ."'n";
          sleep(rand(1,3)) ;
      }
      function for_cik($cik) {
          //doing work
          // lock() ; ?
          Log_NIK::getInstance()->write_line($log) ; //write this 'safely'
          //unlock() ; ?
      }
  }

我搜索了,但发现只有特定于语言的建议(对于其他语言)。c#/java等)

编辑:

write_line函数是:

    function write_line($line){
        file_put_contents($this->logFileName,$line."'n",FILE_APPEND) ;
    }

您没有显示所有的代码。如果您在某处使用file_put_contents(),则需要传递LOCK_EX标志。

file_put_contents('file.txt', 'content', LOCK_EX | FILE_APPEND);

在开始时搜索某个特定文件的存在。如果不存在——创造它,然后最终抛弃它。如果另一个线程试图写入,它将无法这样做。

$fp = fopen(dirname(__FILE__) . DIRECTORY_SEPARATOR . "somefile.txt", "w+");
if (flock($fp, LOCK_EX | LOCK_NB)) { 
    // do your stuff here
    flock($fp, LOCK_UN); // release the lock
    unlink (dirname(__FILE__) . DIRECTORY_SEPARATOR . "somefile.txt");
}
fclose($fp);