Doctrine Entity Manager with PThreads and Symfony2
Hi krakjoe,
I'm currentliy working with a thread safe version of PHP 5.6.2 with pthreads, Symfony2 and Doctrine2. All works fine so far, but I have some problems with the EntityManager of Doctrine2. I can't pass it from the standard Symfony2 context into my thread, because it can't be serialized. In this case $this->em is my Doctrine Entity Manager.
$pool = new \Pool(4, ThreadedWorker::class, [serialize($asyncFileStorage), serialize($this->em)]);
foreach ($files as $file) {
$this->em->refresh($file);
$pool->submit(new AsyncArticleXmlConverter(serialize($file), serialize($this->product), $this>pubDate));
}
$pool->shutdown();
$pool->collect(function($work){
return $work->isGarbage();
});
Doesn't work. I always get the following error.
[PDOException]
You cannot serialize or unserialize PDO instances
So i recreated my Symfony2 Container inside of the Worker class and start the threads like this
public function run()
{
require_once '/data/hydra/app/bootstrap.php.cache';
require_once '/data/hydra/app/AppKernel.php';
$kernel = new \AppKernel('dev', true);
$kernel->loadClassCache();
$kernel->boot();
$this->container = $kernel->getContainer();
}
public function start($options = null)
{
return parent::start(PTHREADS_INHERIT_NONE);
}
The container and object access works like a charm, but when I access the database with the Entity Manager, the complete command stops working after the first four threads. Again $this->em is my Doctrine Entity Manager.
$this->em->persist($obj);
// After the flush the command stops working
$this->em->flush();
// Command stops working
$this->em->refresh($obj);
$this->em->remove($obj);
// After the flush the command stops working
$this->em->flush();
Is there a way to handle non-thread-safe objects like the entity manager? I'm trying a lot of different ways to access the database with it, but either it can't be serialized or the command stops working. Any help or hint is appreciated. :-)
+1 same issue
you can try putting non threading compatible object in static members of your threadclass.
The static context of threaded classes is treaded as a thread-local store. No attemp to serialize stuff should happen there if I'm not mistaken.
apeart from that I can't give you any hints, since I don't know Doctrine and Symfony
Thanks @chibisuke :-) Declared the EM as a static member inside of the thread and for now, it's working. Buuuuut now I run into the next problem. I guess it's using up too much memory. Round about 400 Threads running through the process and each of it is using up like 2mb.
On all more complex or bigger objects I call
$var = null; unset($var);
respectively
self::$var = null;
Also i call
$this->setGarbage();
after I'm done with the work.
Inside of my Desctructor I call on all class variables unset and null them. I guess it's the EntityManager as a Static Variable, which is using that much memory. But even after I set it to null, it won't get less.
Tips to track down a leak or how to spare some memory?
Or is this the normal behaviour of the Threads and I just need to resize my PHP-Memory in this case?
each operating system thread got a Stack andits own copy of the binary data of the script.
400 threads is nowhere near efficient programming. This is not java, and you're propably not only developing for windows. To my experience N+1 or N+2 threads is a good start to get a propper CPU Load (where N is the number of virtual CPU Cores).
Well, of course not 400 threads at the same time. 4 threads are running at the same time (4 virtual cores) and all in all there are 400 threads which need to executed. (Collected in a thread pool) The performance is great ( in my testcase, 2min without threads, 30 seconds with threads), and the CPU Load also looks good to me.
But I guess, I fixed it. I passed my Symfony2 Container as a serialized object to the functions of my thread, because there were some errors, while it was a class variable. Now I also declared it as a static, like the entity manager, and my memory doesn't go higher than 40 megabyte. Some adjustments on setting variables to null and some more unsets even speeded it up a little. I guess the serialization wasn't the best idea ...
After some more refactoring, it'll show, if it works proper now. At least I hope so
Does this static member workaroud requires 5.6? I'm having nulls or segfaults with 5.5.9 php (zts) and with the most recent version of pthreads when passing $em (Doctrine), even to only one thread.
Can you please show an example, how should it be done? I've googled my day :S
This is no longer applicable to seven, so closing.
@svenpelster Can you explain how you have recreated the container? I'm trying to getting help here http://stackoverflow.com/questions/32952438/symfony-doctrine-entity-manager-injected-in-thread . For your opinion is possible to use a service as a thread?
@mmeloni As mentioned in the stackoverflow thread: You can't really share the Entity Manager with all Threads. You can create a new manager for each thread, but we never got it 100% perfect. We created a new AppKernel within the Worker. Inside of our threads we accessed the entity manager and container, which we declared as static.
Here is a code snippet: Worker
class Worker extends \Worker
{
public function run()
{
// Loading the Cache and Classes
require_once __DIR__.'/../../../../../app/bootstrap.php.cache';
require_once __DIR__.'/../../../../../app/AppKernel.php';
// Creating a new AppKernel with the given environment
$kernel = new \AppKernel($this->env, $debug);
$kernel->loadClassCache();
$kernel->boot();
// Passing the container
$this->container = serialize($kernel->getContainer());
}
}
Thread
class Thread extends \Collectable
{
public static $em;
public static $container;
public function run()
{
// Get the serialized contrainer
static::$container = unserialize($this->worker->container);
// Create entity manager
static::$em = static::$container->get('doctrine.orm.entity_manager');
...
}
}
I'd like to suggest having a look at appserver.io. They might have solved some of the problems you are encountering with their persistence container.
http://appserver.io/get-started/documentation/1.0/persistence-container.html
https://github.com/appserver-io/appserver/tree/master/src/AppserverIo/Appserver/PersistenceContainer
At a minimum, the code might shed some light to the right direction to take, if there is one.
Scott
@svenpelster Tnx for your help . I have share my works on stackoverflow.
@smolinari Tnx Scott . appserver.io is very interesting. It 's a revolution for php standard patterns . They have solved my problem with a php daemon always running . This approach is new for us and too much complex for our needs for now . But anyway I will keep for future project monitored app.io.
Hello, and you can tell me how the same will be in symfony 4-I was pushed with the same problem but in version 4 no loadClass