tags:

views:

71

answers:

3

I have script with defined class (for instance, Singleton.php). This class implements classic singleton pattern as in PHP manual:

 class Singleton   {
    private static $instance;

    public static function getInstance() 
    {
       if (!isset(self::$instance)) {
           $c = __CLASS__;
           self::$instance = new $c;
       }

       return self::$instance;
    }
    public function run() {
        // bunch of "thread safe" operations
    }  }

$inst = Singleton::getInstance(); 
$inst->run();

Question. If I call this script twice from command line ('php Singleton.php'), will run() method be really "thread safe"? It seems that it will not. I used to imitate single-process run via text file where some flag is stored, but it seems that there might be other cases. Your thoughts?

+1  A: 

Singletons have nothing to do with thread-safety. They are here to only have one instance of an object per process.

so, to answer your question: no, your script is not thread safe. php will start one process (not thread) for each call on the cli. both processes will create an instance of your class and both will try to write the file.

the process to later write the file will win, and overwrite changes from the first process.

knittl
Thanks. That's what I also thought is right.
altern
+1  A: 

PHP is not threaded - it is process oriented. Each invocation of PHP (wether it be commandline or apache instance) is memory independent.

Your singleton will only be unique to that one process.

(oh and instead of doing $c=__CLASS__; $instance = new $c; you should use 'self' like $instance = new self();. Same result, less fuss. Also be sure to set your __construct() private/protected)

Justin
A: 

If you run this script from the command line twice (concurrently, I guess), you will get two completely distinct processes, therefore the thread safety is not an issue: there are no threads here.

Palantir