Tuesday, September 18, 2007

Why to use a daemon ?

In a standard web context, i.e. with a server executing PHP scripts to response clients' requests, every action asked by the clients is executed during the time the server build the response. For example sending a email to a lot of recipients will cause the execution of the following actions :
  • Get every email addresses the mailing should go to.
  • Foreach email addresses send the mail
These actions, more precisely the one sending the mail, can take some time, and repeating it hundreds of times could cause a timeout to the client's request. What happens then ? The emails not send before the timeout will never be sent, and the system will remain in an knwow state.

Asynchronous calls

To avoid this bad behaviour, a method called asynchronous call can be used. The principle is the following : insead of doing the whole action during the response, the action is put into a queue and is performed by another process which is independant of the client's request, process call "daemon".

The daemon will then look at the queue to check if there is some action to take, and do them until the queue is empty. When the queue is empty, it will wait until some new job come into the queue.

Asychronous calls are then implemented with two parts :
  • A queue which will contain the jobs to do
  • A daemon which will do the jobs in the queue.
This two parts will be largely used later in the concept and in the implementation.

Monday, September 17, 2007


This is a step-by-step tutorial to build a multithreaded daemon in PHP. I will point out several problems caused by a greedy implementation and will give some ways to solve them. I will also have a look at which functions are provided by PHP, what are their advantages and their drawbacks, and how to use them. I will finally give a working implementation of a class that would expose every functions needed to run such a daemon. The implementation will be written in PHP5.

Below are the steps of this tutorial :

  1. Introduction (this part)
  2. Why to use a daemon ?
  3. What is provided by PHP to handle multithreading ?
  4. Roots of a conceptual implementation
  5. The basic implementation of the multithreading class
  6. Limitations of the basic implementation and future work.