Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threads in PHP?

I am creating a web application using zend, here I create an interface from where user-A can send email to more than one user(s) & it works excellent but it slow the execution time because of which user-A wait too much for the "acknowledged response" ( which will show after the emails have sent. )

In Java there are "Threads" by which we can perform that task (send emails) & it does not slow the rest application.

Is there any technique in PHP/Zend just like in Java by which we can divide our tasks which could take much time eg: sending emails.

like image 716
PHP Ferrari Avatar asked Apr 06 '10 14:04

PHP Ferrari


People also ask

Does PHP use multithreading?

PHP applications, undoubtedly work effectively with multithreading capabilities. Multithreading is something similar to multitasking, but it enables to process multiple jobs at one time, rather than on multiple processes.

Is PHP single threaded?

PHP is NOT single threaded by nature. It is, however, the case that the most common installation of PHP on unix systems is a single threaded setup, as is the most common Apache installation, and nginx doesn't have a thread based architecture whatever.

What is thread safe in PHP?

What does thread safety mean when downloading PHP? Thread Safety means that binary can work in a multithreaded webserver context, such as Apache 2 on Windows. Thread Safety works by creating a local storage copy in each thread, so that the data won't collide with another thread.


1 Answers

EDIT (thanks @Efazati, there seems to be new development in this direction)

http://php.net/manual/en/book.pthreads.php
Caution: (from here on the bottom):

pthreads was, and is, an experiment with pretty good results. Any of its limitations or features may change at any time; [...]

/EDIT

No threads in PHP!

The workaround is to store jobs in a queue (say rows in a table with the emails) and have a cronjob call your php script at a given interval (say 2 minutes) and poll for jobs. When jobs present fetch a few (depending on your php's install timeout) and send emails.

The main idea to defer execution:

  • main script adds jobs in the queue
  • cron script sends them in tiny slices

Gotchas:

  • make sure u don't send an email without deleting from queue (worst case would be if a user rescieves some spam at 2 mins interval ...)
  • make sure you don't delete a job without executing it first ...
  • handle bouncing email using a score algorithm
like image 189
clyfe Avatar answered Oct 16 '22 23:10

clyfe