SlideShare uma empresa Scribd logo
1 de 44
Cutting Back Processing Time
Executing multiple things at the same time
Meet Ed
PHP was not made for it, Moody.
A lot happen since 1995, Ed.
There are better options rather than use PHP
for that, Moody.
There can be, and that does not mean that
we should ignore it, Ed.
Bla, bla, bla, Moody.
Bla, bla, bla, Ed.
I don’t like to use PHP for that, Moody.
Screw you, Ed.
Screw you, Ed.
PHP supports it, we just need to know what
we’re doing.
Concurrency & Parallelism
Concurrency
Parallelism
Thread, Process & Fork
Thread
• Is the smallest sequence of programmed instructions
• May also be called as “task”
• When in the same process they share resources such as memory
Process
• The operating system keeps its processes separate and allocates the
resources they need
• Every process has an ID, a parent, an owner, and a session
• Contains state of all threads executing in a program
• Process may be made up of multiple threads of execution that
execute instructions concurrently
One Process, Multiple Threads
Multiple Processes & Multiple Threads
Fork
• When a process creates a copy of itself
Implementing in PHP
pthreads
• Implementation of POSIX Threads in PHP
• Works on Unix-like and Windows
• Requires PHP with ZTS (Zend Thread Safety) enabled (--enable-
maintainer-zts or --enable-zts on Windows)
• First stable version in 2014
pthreads
final class WorkerThreads extends Thread
{
private $workerId;
public function __construct(int $workerId)
{
$this->workerId = $workerId;
}
public function run()
{
sleep(rand(0, 1));
echo sprintf('Worker "%s" ran', $this->workerId).PHP_EOL;
}
}
pthreads
for ($index = 1; $index <= 5; ++$index) {
$worker = new WorkerThreads($index);
$worker->start();
}
echo 'Lekker threads!';
pthreads
$ php pthreads.php
Worker "5" ran
Worker "1" ran
Worker "0" ran
Worker "4" ran
Worker "2" ran
Lekker threads!
Worker "3" ran
pthreads
final class WorkerPool extends Pool
{
public function wait(): void
{
foreach ($this->workers as $worker) {
$worker->join();
}
}
}
pthreads
$pool = new WorkerPool(5);
for ($index = 1; $index <= 5; ++$index) {
$pool->submit(new WorkerThreads($index));
}
$pool->wait();
echo 'Lekker threads!';
pthreads
$ php pthreads.php
Worker "5" ran
Worker "1" ran
Worker "0" ran
Worker "2" ran
Worker "4" ran
Worker "3" ran
Lekker threads!
PCNTL
• Available since PHP 4
• Works only on Unix-like platforms
• Creation, program execution, signal handling and process
termination
• Does not work on web servers
PCNTL
$pid = pcntl_fork();
if ($pid == -1) {
error_log('You have failed this fork...');
exit(1);
}
if ($pid > 0) {
echo sprintf(
'I am the Parent Process and my PID is %d. My child's PID is %d’.PHP_EOL,
getmypid(),
$pid
);
exit();
}
echo 'I am the Child Process and my PID is '.getmypid()." xf0x9fx91xb6";
PCNTL
$ php fork.php
I am the Parent Process and my PID is 45179. My child's PID is 45180
I am the Child Process and my PID is 45180 👶
POSIX
• Available since PHP 4
• Enabled by default the PHP is compiled
• Interface for POSIX (Portable Operating System Interface) functions
• Works only on Unix-like systems
• Manage process, sessions, groups, users and files
POSIX
$uid = 501;
if (posix_setuid($uid) === false) {
error_log(posix_strerror(posix_get_last_error()));
exit(3);
}
$gid = 20;
if (posix_setgid($gid) === false) {
error_log(posix_strerror(posix_get_last_error()));
exit(4);
}
echo 'My PID is '.getmypid().', my UID is '.posix_geteuid().', my GID is '.posix_getgid();
POSIX
$ php fork+posix.php
I am the Parent Process and my PID is 45271. My child's PID is 45272
My PID is 45272, my UID is 501, my GID is 20
Inter-Process Communication
Options for IPC
• Files
• Signals (pcntl_signal(), pcntl_signal_dispatch(), posix_kill(), etc)
• Semaphores (sem_*, load balanced messages)
• Shared Memory (shm_*)
• Message Queue
• Sockets
• DBMS
Tricks
Forks share nothing
• Ensure yours new-born process can write and read files with umask(0)
• Do not use the same connections
• Replace file descriptors (STDIN, STDOUT and STDERR) or ensure you
don’t write/read them
• Use a lot of logs
• Replace the working directory with something you know that exists, like
chdir(__DIR__)
Daemons are independent
• Fork off and die
• Use the init session by calling posix_setsid()
• Save the PID somewhere
About Forks
• They are single core
• PHP is not multi-threaded by default
• Forks will be created in the same CPU of its parents
• Easy to overload a server
About Threads
• The memory_limit will be respected
• Does not make sense to use on a single core
Conclusion
Henrique Moody
Software developer focused on PHP.
Addicted to code, patterns, and
development methodologies. Open Source
enthusiast, publisher and contributor of
many projects, and core developer of the
Respect components. Brazilian based in
the Amsterdam working for Werkspot.
@henriquemoody
@henriquemoody
References
http://man7.org/linux/man-pages/man7/signal.7.html;
http://www.win.tue.nl/~aeb/linux/lk/lk-10.html;
https://en.wikipedia.org/wiki/Concurrency_(computer_science);
https://en.wikipedia.org/wiki/Cron;
https://en.wikipedia.org/wiki/Daemon_(computing);
https://en.wikipedia.org/wiki/Init;
https://en.wikipedia.org/wiki/Parallel_computing;
https://en.wikipedia.org/wiki/POSIX; https://secure.php.net/ChangeLog-
4.php; https://secure.php.net/cli; https://secure.php.net/ncurses;
https://secure.php.net/newt; https://secure.php.net/pcntl;
https://secure.php.net/posix; https://secure.php.net/pthreads;
https://secure.php.net/readline; https://secure.php.net/readline;
https://secure.php.net/sem; https://www.slideshare.net/jkeppens/php-in-

Mais conteúdo relacionado

Mais procurados

The Php Life Cycle
The Php Life CycleThe Php Life Cycle
The Php Life Cycle
Xinchen Hui
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappers
Positive Hack Days
 
Asynchronous I/O in PHP
Asynchronous I/O in PHPAsynchronous I/O in PHP
Asynchronous I/O in PHP
Thomas Weinert
 

Mais procurados (20)

Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Asynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time MessagingAsynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time Messaging
 
PuppetDB, Puppet Explorer and puppetdbquery
PuppetDB, Puppet Explorer and puppetdbqueryPuppetDB, Puppet Explorer and puppetdbquery
PuppetDB, Puppet Explorer and puppetdbquery
 
お題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part Aお題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part A
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
The Php Life Cycle
The Php Life CycleThe Php Life Cycle
The Php Life Cycle
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.js
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappers
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
 
Asynchronous I/O in PHP
Asynchronous I/O in PHPAsynchronous I/O in PHP
Asynchronous I/O in PHP
 
Php in 2013 (Web-5 2013 conference)
Php in 2013 (Web-5 2013 conference)Php in 2013 (Web-5 2013 conference)
Php in 2013 (Web-5 2013 conference)
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
 
Functional Hostnames and Why they are Bad
Functional Hostnames and Why they are BadFunctional Hostnames and Why they are Bad
Functional Hostnames and Why they are Bad
 
Oliver hookins puppetcamp2011
Oliver hookins puppetcamp2011Oliver hookins puppetcamp2011
Oliver hookins puppetcamp2011
 
PHP 7 new engine
PHP 7 new enginePHP 7 new engine
PHP 7 new engine
 
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
 
Python build your security tools.pdf
Python build your security tools.pdfPython build your security tools.pdf
Python build your security tools.pdf
 
Relayd: a load balancer for OpenBSD
Relayd: a load balancer for OpenBSD Relayd: a load balancer for OpenBSD
Relayd: a load balancer for OpenBSD
 
NoSQL Injections in Node.js - The case of MongoDB
NoSQL Injections in Node.js - The case of MongoDBNoSQL Injections in Node.js - The case of MongoDB
NoSQL Injections in Node.js - The case of MongoDB
 
React PHP: the NodeJS challenger
React PHP: the NodeJS challengerReact PHP: the NodeJS challenger
React PHP: the NodeJS challenger
 

Semelhante a Cutting Back Processing Time

Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
webhostingguy
 
Powershell Training
Powershell TrainingPowershell Training
Powershell Training
Fahad Noaman
 

Semelhante a Cutting Back Processing Time (20)

Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
Portable PHP
Portable PHPPortable PHP
Portable PHP
 
PowerShell - Be A Cool Blue Kid
PowerShell - Be A Cool Blue KidPowerShell - Be A Cool Blue Kid
PowerShell - Be A Cool Blue Kid
 
PHP language presentation
PHP language presentationPHP language presentation
PHP language presentation
 
posix.pdf
posix.pdfposix.pdf
posix.pdf
 
Lecture2 process structure and programming
Lecture2   process structure and programmingLecture2   process structure and programming
Lecture2 process structure and programming
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
Powershell Training
Powershell TrainingPowershell Training
Powershell Training
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
 
concurrency
concurrencyconcurrency
concurrency
 
Process injection - Malware style
Process injection - Malware styleProcess injection - Malware style
Process injection - Malware style
 
Php with mysql ppt
Php with mysql pptPhp with mysql ppt
Php with mysql ppt
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
 
Python and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementPython and Oracle : allies for best of data management
Python and Oracle : allies for best of data management
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginners
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Systems Programming Assignment Help - Processes
Systems Programming Assignment Help - ProcessesSystems Programming Assignment Help - Processes
Systems Programming Assignment Help - Processes
 
Php
PhpPhp
Php
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 

Mais de Henrique Moody (6)

Commit to good commit messages
Commit to good commit messagesCommit to good commit messages
Commit to good commit messages
 
O esquecido do PHP
O esquecido do PHPO esquecido do PHP
O esquecido do PHP
 
TestFest - Respect\Validation 1.0
TestFest - Respect\Validation 1.0TestFest - Respect\Validation 1.0
TestFest - Respect\Validation 1.0
 
Introdução ao Respect\Validation (1.0)
Introdução ao Respect\Validation (1.0)Introdução ao Respect\Validation (1.0)
Introdução ao Respect\Validation (1.0)
 
PHP e seus demônios
PHP e seus demôniosPHP e seus demônios
PHP e seus demônios
 
PHP-CLI em 7 passos
PHP-CLI em 7 passosPHP-CLI em 7 passos
PHP-CLI em 7 passos
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

Cutting Back Processing Time