SitePoint Sponsor

User Tag List

Results 1 to 1 of 1
  1. #1
    SitePoint Enthusiast dgx's Avatar
    Join Date
    Aug 2005
    Location
    The Czech Republic
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Thread-safe scripting: atomic file operations - final solution

    This refers to Threadsafe file access - solution topic.

    PHP implements important file functions like file_get_contents or file_put_contents as non-atomic. So this code executed twice (or more) simultaneously leads to generate 'ERROR':

    PHP Code:
    $original str_repeat('LaTrine'10000);
    $counter 1000;

    while (
    $counter--) {
      
    // write
      
    file_put_contents('file'$original);

      
    // read
      
    $content file_get_contents('file');

      
    // compare
      
    if ($original !== $content) die('ERROR');


    To build thread-safe applications is very important, but nearly nobody it does. So there is a universal and easy solution - NSafeStream.

    NSafeStream registers stream wrapper. And you can use standard PHP functions as atomic, resp. thread-safe.

    Usage:

    PHP Code:
    // prepend filename with "safe://"
    $handle fopen('safe://test.txt''x');
    // actually a temporary file is created

    fwrite($handle'La Trine');

    fclose($handle);
    // and now it renames temporary file to test.txt

    // unlink is supported too
    unlink('safe://test.txt');

    // every functions are now thread-safe and atomic!
    file_put_contents('safe://test.txt'$content);

    $ini parse_ini_file('safe://autoload.ini'); 
    Download

    NSafeStream version 0.3, PHP4 & PHP5
    Last edited by dgx; Nov 4, 2006 at 21:23.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •