SlideShare une entreprise Scribd logo
1  sur  16
Télécharger pour lire hors ligne
PHP DISTRIBUÍDO E
PARALELO
Multithread + Stream Sockets
Diana Ungaro Arnos
tech daymio @ high stakes academy
evangelist @ PHP Women
EU USO LOAD BALANCER, MEU SISTEMA É DISTRIBUÍDO.
NÃO!
DISTRIBUIR ACESSOS NÃO É O MESMO QUE DISTRIBUIR PROCESSAMENTO.
LOAD BALANCER
SERVIDOR
APLICAÇÃO
SERVIDOR
APLICAÇÃO
SERVIDOR
APLICAÇÃO
O PROCESSAMENTO DA TAREFA É DISTRIBUÍDO EM PARALELO ENTRE MÁQUINAS DIFERENTES
APLICAÇÃO
SERVIDOR SERVIDOR SERVIDOR
SOLICITA TAREFA X
X PARTE 1 X PARTE 2 X PARTE 3
XML
XML
XML
XML
MÁQUINA 1
XML
MÁQUINA 2
XML
MÁQUINA 3
XML
PROCESSAMENTO PARALELO DISTRIBUÍDO COM PHP?
MULTI THREAD? DISTRIBUÍDO E PARALELO?
PTHREADS
PTHREADS + STREAM
SOCKETS
PTHREADS
PHP COMPILADO COM ZTS (THREAD SAFETY)
V3 : FOI REESCRITO E É 100% COMPATÍVEL COM PHP 7
PARA USAR COM PHP5: V2
É SEGURO
PTHREADS
class SimpleThreadExample extends Thread
{
/** @var int */
private $workerId = 0;
public function __construct($id)
{
$this->workerId = $id;
}
public function run()
{
echo "Thread " . $this->workerId . " começou a executar.n";
sleep(rand(0, 3));
echo "Thread " . $this->workerId . " parou de executar.n";
}
}
PTHREADS
$workerPool = [];
foreach (range(0, 10) as $id)
{
$workerPool[$id] = new SimpleThreadExample($id);
$workerPool[$id]->start();
}
foreach (range(0, 10) as $id)
{
$workerPool[$id]->join();
}
PTHREADS
Thread 0 começou a executar.
Thread 1 começou a executar.
Thread 2 começou a executar.
Thread 0 parou de executar.
Thread 3 começou a executar.
Thread 1 parou de executar.
Thread 4 começou a executar.
Thread 2 parou de executar.
Thread 3 parou de executar.
Thread 4 parou de executar.
STREAM SOCKETS
SOCKETS: MECANISMO DE COMUNICAÇÃO ENTRE PROCESSOS
- EM MODELO CLIENTE/SERVIDOR => 1P + PORTA. EX.: 127.0.0.1:80
STREAM SOCKETS:
$server = stream_socket_server(”tcp://192.168.33.99”, $errorNum, $errorMsg);
while ($conn = stream_socket_accept($server)) { //código}
$client = stream_socket_client("tcp://$this->workerHost", $errorNum, $errorMsg, 10);
fclose($client);
- fgets(), fclose(), fread(), ETC…
DISTRIBUINDO O PROCESSAMENTO
NO EXEMPLO DO XML:
- UM SCRIPT DE SCRAPPING QUE RECEBE O PEDAÇO DE XML
class Scrapper
{
//código
public function run()
{
$server = stream_socket_server("tcp://$this->socket", $errorNum, $errorMsg);
while ($conn = stream_socket_accept($server)) {
// código de scrapping
}
fclose($server);
}
}
$scrapper= new Scrapper($argv);
$scrapper >run();
DISTRIBUINDO O PROCESSAMENTO
- O CLIENT QUE FAZ A REQUISIÇÃO
class Client
{
//código
private function sendFilePiecesToWorkers($xml)
{
//código
foreach ($this->scrappersAdderss as $scrapper) {
$this->senderPool[$scrapper] = new Sender($scrapper, $xml);
$this->senderPool[$ scrapper]->start();
}
foreach ($this->senderPool as $sender) {
$sender->join();
echo "Encerrando thread...n";
array_push($results, $sender->result);
}
}
}
DISTRIBUINDO O PROCESSAMENTO
- O SENDER, RESPONSÁVEL POR ENVIAR OS PEDAÇOS AOS SCRAPPERS
class Sender extends Thread
{
//código
public function run()
{
$client = stream_socket_client("tcp://$this->scrapperHost", $errorNum, $errorMsg, 10);
//código
foreach ($this->scrappersAdderss as $scrapper) {
//código
$this->result = stream_get_contents($client);
}
fclose($client);
}
}
OBRIGADA!
https://joind.in/talk/f0272
@dianaarnos
INSTAGRAM E TWITTER
FACEBOOK
fb.com/dianaarnos

Contenu connexe

Similaire à PHP distribuído e paralelo: multithread + stream sockets

Curso: Redes y telecomunicaciones: 07 Protoclos TCP/IP
Curso: Redes y telecomunicaciones: 07 Protoclos TCP/IPCurso: Redes y telecomunicaciones: 07 Protoclos TCP/IP
Curso: Redes y telecomunicaciones: 07 Protoclos TCP/IPJack Daniel Cáceres Meza
 
Computer network (4)
Computer network (4)Computer network (4)
Computer network (4)NYversity
 
WSO2 SOA with C and C++
WSO2 SOA with C and C++WSO2 SOA with C and C++
WSO2 SOA with C and C++WSO2
 
Use perl creating web services with xml rpc
Use perl creating web services with xml rpcUse perl creating web services with xml rpc
Use perl creating web services with xml rpcJohnny Pork
 
Training Slides: 153 - Working with the CLI
Training Slides: 153 - Working with the CLITraining Slides: 153 - Working with the CLI
Training Slides: 153 - Working with the CLIContinuent
 
Introduction to Thrift
Introduction to ThriftIntroduction to Thrift
Introduction to ThriftDvir Volk
 
ZeroMQ - Sockets on steroids!
ZeroMQ - Sockets on steroids!ZeroMQ - Sockets on steroids!
ZeroMQ - Sockets on steroids!Pedro Januário
 
Measuring maintainability; software metrics explained
Measuring maintainability; software metrics explainedMeasuring maintainability; software metrics explained
Measuring maintainability; software metrics explainedDennis de Greef
 
Session Server - Maintaing State between several Servers
Session Server - Maintaing State between several ServersSession Server - Maintaing State between several Servers
Session Server - Maintaing State between several ServersStephan Schmidt
 
INFA 620Laboratory 4 Configuring a FirewallIn this exercise.docx
INFA 620Laboratory 4 Configuring a FirewallIn this exercise.docxINFA 620Laboratory 4 Configuring a FirewallIn this exercise.docx
INFA 620Laboratory 4 Configuring a FirewallIn this exercise.docxcarliotwaycave
 
Lindsay distributed geventzmq
Lindsay distributed geventzmqLindsay distributed geventzmq
Lindsay distributed geventzmqRobin Xiao
 
Wfuzz para Penetration Testers
Wfuzz para Penetration TestersWfuzz para Penetration Testers
Wfuzz para Penetration TestersSource Conference
 
Cassandra 2.1 boot camp, Overview
Cassandra 2.1 boot camp, OverviewCassandra 2.1 boot camp, Overview
Cassandra 2.1 boot camp, OverviewJoshua McKenzie
 
Taming Deployment With Smart Frog
Taming Deployment With Smart FrogTaming Deployment With Smart Frog
Taming Deployment With Smart FrogSteve Loughran
 
002 hbase clientapi
002 hbase clientapi002 hbase clientapi
002 hbase clientapiScott Miao
 

Similaire à PHP distribuído e paralelo: multithread + stream sockets (20)

Curso: Redes y telecomunicaciones: 07 Protoclos TCP/IP
Curso: Redes y telecomunicaciones: 07 Protoclos TCP/IPCurso: Redes y telecomunicaciones: 07 Protoclos TCP/IP
Curso: Redes y telecomunicaciones: 07 Protoclos TCP/IP
 
Computer network (4)
Computer network (4)Computer network (4)
Computer network (4)
 
WSO2 SOA with C and C++
WSO2 SOA with C and C++WSO2 SOA with C and C++
WSO2 SOA with C and C++
 
Use perl creating web services with xml rpc
Use perl creating web services with xml rpcUse perl creating web services with xml rpc
Use perl creating web services with xml rpc
 
Rust Hack
Rust HackRust Hack
Rust Hack
 
Training Slides: 153 - Working with the CLI
Training Slides: 153 - Working with the CLITraining Slides: 153 - Working with the CLI
Training Slides: 153 - Working with the CLI
 
HARDENING IN APACHE WEB SERVER
HARDENING IN APACHE WEB SERVERHARDENING IN APACHE WEB SERVER
HARDENING IN APACHE WEB SERVER
 
Introduction to Thrift
Introduction to ThriftIntroduction to Thrift
Introduction to Thrift
 
ZeroMQ - Sockets on steroids!
ZeroMQ - Sockets on steroids!ZeroMQ - Sockets on steroids!
ZeroMQ - Sockets on steroids!
 
Measuring maintainability; software metrics explained
Measuring maintainability; software metrics explainedMeasuring maintainability; software metrics explained
Measuring maintainability; software metrics explained
 
Session Server - Maintaing State between several Servers
Session Server - Maintaing State between several ServersSession Server - Maintaing State between several Servers
Session Server - Maintaing State between several Servers
 
INFA 620Laboratory 4 Configuring a FirewallIn this exercise.docx
INFA 620Laboratory 4 Configuring a FirewallIn this exercise.docxINFA 620Laboratory 4 Configuring a FirewallIn this exercise.docx
INFA 620Laboratory 4 Configuring a FirewallIn this exercise.docx
 
Lindsay distributed geventzmq
Lindsay distributed geventzmqLindsay distributed geventzmq
Lindsay distributed geventzmq
 
Wfuzz para Penetration Testers
Wfuzz para Penetration TestersWfuzz para Penetration Testers
Wfuzz para Penetration Testers
 
06.pptx
06.pptx06.pptx
06.pptx
 
Cassandra 2.1 boot camp, Overview
Cassandra 2.1 boot camp, OverviewCassandra 2.1 boot camp, Overview
Cassandra 2.1 boot camp, Overview
 
Security in NodeJS applications
Security in NodeJS applicationsSecurity in NodeJS applications
Security in NodeJS applications
 
Attques web
Attques webAttques web
Attques web
 
Taming Deployment With Smart Frog
Taming Deployment With Smart FrogTaming Deployment With Smart Frog
Taming Deployment With Smart Frog
 
002 hbase clientapi
002 hbase clientapi002 hbase clientapi
002 hbase clientapi
 

Plus de Diana Ungaro Arnos

trabalho remoto é questão de cultura - 19o encontro locaweb
trabalho remoto é questão de cultura - 19o encontro locawebtrabalho remoto é questão de cultura - 19o encontro locaweb
trabalho remoto é questão de cultura - 19o encontro locawebDiana Ungaro Arnos
 
API 101: o que é, onde vive, como se alimenta?
API 101: o que é, onde vive, como se alimenta?API 101: o que é, onde vive, como se alimenta?
API 101: o que é, onde vive, como se alimenta?Diana Ungaro Arnos
 
APIs: o que são, onde vivem e como se alimentam
APIs: o que são, onde vivem e como se alimentamAPIs: o que são, onde vivem e como se alimentam
APIs: o que são, onde vivem e como se alimentamDiana Ungaro Arnos
 
PHPExperience 2016 - Pirâmide de Testes
PHPExperience 2016 - Pirâmide de TestesPHPExperience 2016 - Pirâmide de Testes
PHPExperience 2016 - Pirâmide de TestesDiana Ungaro Arnos
 
Sistemas Distribuídos e PHP - Darkmira Tour BR 2016
Sistemas Distribuídos e PHP - Darkmira Tour BR 2016Sistemas Distribuídos e PHP - Darkmira Tour BR 2016
Sistemas Distribuídos e PHP - Darkmira Tour BR 2016Diana Ungaro Arnos
 
Testes O que são e para que servem? - LadyTalks
Testes O que são e para que servem? - LadyTalksTestes O que são e para que servem? - LadyTalks
Testes O que são e para que servem? - LadyTalksDiana Ungaro Arnos
 
PHP Expericence 2015 - Testes Unitários - Existe vida antes do TDD
PHP Expericence 2015 - Testes Unitários - Existe vida antes do TDDPHP Expericence 2015 - Testes Unitários - Existe vida antes do TDD
PHP Expericence 2015 - Testes Unitários - Existe vida antes do TDDDiana Ungaro Arnos
 
Testes: existe vida antes do TDD
Testes: existe vida antes do TDDTestes: existe vida antes do TDD
Testes: existe vida antes do TDDDiana Ungaro Arnos
 

Plus de Diana Ungaro Arnos (8)

trabalho remoto é questão de cultura - 19o encontro locaweb
trabalho remoto é questão de cultura - 19o encontro locawebtrabalho remoto é questão de cultura - 19o encontro locaweb
trabalho remoto é questão de cultura - 19o encontro locaweb
 
API 101: o que é, onde vive, como se alimenta?
API 101: o que é, onde vive, como se alimenta?API 101: o que é, onde vive, como se alimenta?
API 101: o que é, onde vive, como se alimenta?
 
APIs: o que são, onde vivem e como se alimentam
APIs: o que são, onde vivem e como se alimentamAPIs: o que são, onde vivem e como se alimentam
APIs: o que são, onde vivem e como se alimentam
 
PHPExperience 2016 - Pirâmide de Testes
PHPExperience 2016 - Pirâmide de TestesPHPExperience 2016 - Pirâmide de Testes
PHPExperience 2016 - Pirâmide de Testes
 
Sistemas Distribuídos e PHP - Darkmira Tour BR 2016
Sistemas Distribuídos e PHP - Darkmira Tour BR 2016Sistemas Distribuídos e PHP - Darkmira Tour BR 2016
Sistemas Distribuídos e PHP - Darkmira Tour BR 2016
 
Testes O que são e para que servem? - LadyTalks
Testes O que são e para que servem? - LadyTalksTestes O que são e para que servem? - LadyTalks
Testes O que são e para que servem? - LadyTalks
 
PHP Expericence 2015 - Testes Unitários - Existe vida antes do TDD
PHP Expericence 2015 - Testes Unitários - Existe vida antes do TDDPHP Expericence 2015 - Testes Unitários - Existe vida antes do TDD
PHP Expericence 2015 - Testes Unitários - Existe vida antes do TDD
 
Testes: existe vida antes do TDD
Testes: existe vida antes do TDDTestes: existe vida antes do TDD
Testes: existe vida antes do TDD
 

Dernier

Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 

Dernier (20)

Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 

PHP distribuído e paralelo: multithread + stream sockets

  • 2. Diana Ungaro Arnos tech daymio @ high stakes academy evangelist @ PHP Women
  • 3. EU USO LOAD BALANCER, MEU SISTEMA É DISTRIBUÍDO. NÃO!
  • 4. DISTRIBUIR ACESSOS NÃO É O MESMO QUE DISTRIBUIR PROCESSAMENTO. LOAD BALANCER SERVIDOR APLICAÇÃO SERVIDOR APLICAÇÃO SERVIDOR APLICAÇÃO
  • 5. O PROCESSAMENTO DA TAREFA É DISTRIBUÍDO EM PARALELO ENTRE MÁQUINAS DIFERENTES APLICAÇÃO SERVIDOR SERVIDOR SERVIDOR SOLICITA TAREFA X X PARTE 1 X PARTE 2 X PARTE 3
  • 7. PROCESSAMENTO PARALELO DISTRIBUÍDO COM PHP? MULTI THREAD? DISTRIBUÍDO E PARALELO? PTHREADS PTHREADS + STREAM SOCKETS
  • 8. PTHREADS PHP COMPILADO COM ZTS (THREAD SAFETY) V3 : FOI REESCRITO E É 100% COMPATÍVEL COM PHP 7 PARA USAR COM PHP5: V2 É SEGURO
  • 9. PTHREADS class SimpleThreadExample extends Thread { /** @var int */ private $workerId = 0; public function __construct($id) { $this->workerId = $id; } public function run() { echo "Thread " . $this->workerId . " começou a executar.n"; sleep(rand(0, 3)); echo "Thread " . $this->workerId . " parou de executar.n"; } }
  • 10. PTHREADS $workerPool = []; foreach (range(0, 10) as $id) { $workerPool[$id] = new SimpleThreadExample($id); $workerPool[$id]->start(); } foreach (range(0, 10) as $id) { $workerPool[$id]->join(); }
  • 11. PTHREADS Thread 0 começou a executar. Thread 1 começou a executar. Thread 2 começou a executar. Thread 0 parou de executar. Thread 3 começou a executar. Thread 1 parou de executar. Thread 4 começou a executar. Thread 2 parou de executar. Thread 3 parou de executar. Thread 4 parou de executar.
  • 12. STREAM SOCKETS SOCKETS: MECANISMO DE COMUNICAÇÃO ENTRE PROCESSOS - EM MODELO CLIENTE/SERVIDOR => 1P + PORTA. EX.: 127.0.0.1:80 STREAM SOCKETS: $server = stream_socket_server(”tcp://192.168.33.99”, $errorNum, $errorMsg); while ($conn = stream_socket_accept($server)) { //código} $client = stream_socket_client("tcp://$this->workerHost", $errorNum, $errorMsg, 10); fclose($client); - fgets(), fclose(), fread(), ETC…
  • 13. DISTRIBUINDO O PROCESSAMENTO NO EXEMPLO DO XML: - UM SCRIPT DE SCRAPPING QUE RECEBE O PEDAÇO DE XML class Scrapper { //código public function run() { $server = stream_socket_server("tcp://$this->socket", $errorNum, $errorMsg); while ($conn = stream_socket_accept($server)) { // código de scrapping } fclose($server); } } $scrapper= new Scrapper($argv); $scrapper >run();
  • 14. DISTRIBUINDO O PROCESSAMENTO - O CLIENT QUE FAZ A REQUISIÇÃO class Client { //código private function sendFilePiecesToWorkers($xml) { //código foreach ($this->scrappersAdderss as $scrapper) { $this->senderPool[$scrapper] = new Sender($scrapper, $xml); $this->senderPool[$ scrapper]->start(); } foreach ($this->senderPool as $sender) { $sender->join(); echo "Encerrando thread...n"; array_push($results, $sender->result); } } }
  • 15. DISTRIBUINDO O PROCESSAMENTO - O SENDER, RESPONSÁVEL POR ENVIAR OS PEDAÇOS AOS SCRAPPERS class Sender extends Thread { //código public function run() { $client = stream_socket_client("tcp://$this->scrapperHost", $errorNum, $errorMsg, 10); //código foreach ($this->scrappersAdderss as $scrapper) { //código $this->result = stream_get_contents($client); } fclose($client); } }