11
From of that question, I was curious to learn more about the subject, so researching further, I came across more doubt on the subject. Because I saw that there is a string of ways to use Threads.
We can see threads as small processes. The big difference with threads is that they share the same resources and memory addressing. That is, it is as if we had a process that divided into smaller processes, where there is a switching between them, each one running a little (as it happens in processes), but now they share the same data and resources, and have the same goal, work together. And I found it curious, since sometimes I had to pick up enough to improve the performance of complex systems that are still very slow, and that need to use sub systems to improve their performance.
Considering my case, in a future implementation, I would like to know exactly what changes between the three examples below, and when I should use one or the other and vise-versa:
Example of Fork:
$pid = pcntl_fork();
if ($pid == -1) {
die('Erro ao lançar thread');
} else if ($pid) {
// thread principal
//aguardamos a thread child terminar
pcntl_wait($status);
echo "Processo child terminado\n";
exit(0);
} else {
//thread secundario
//mudamos para um usuário não privilegiado
posix_setuid(1000);
posix_setgid(1000);
//colocamos a thread para fazer algo,
//ate que uma condição seja satisfeita e ela termine
$i=0;
while(true){
if (file_exists('/tmp/stop')){
echo "Terminado thread";
exit(0);
}
echo "Iteração : ". ++$i . "\n";
sleep(2);
}
}
Thread Example:
// Classe que aguarda um tempo aleatorio e depois imprime algo na tela
class AguardaRand extends Thread {
// ID da thread (usado para identificar a ordem que as threads terminaram)
protected $id;
// Construtor que apenas atribui um ID para identificar a thread
public function __construct($id) {
$this->id = $id;
}
// Metodo principal da thread, que sera acionado quando chamarmos "start"
public function run() {
// Sortear um numero entre 1 e 4
$tempo_rand = mt_rand(1, 4);
// Aguardar o tempo sorteado
sleep($tempo_rand);
// Imprimir quem e' a thread e quanto tempo ela aguardou
printf(
"Sou a thread %d e aguardei %d segundos\n",
$this->id,
$tempo_rand
);
}
}
//Execucao do codigo
// Criar um vetor com 10 threads do mesmo tipo
$vetor = array();
for ($id = 0; $id < 10; $id++) {
$vetor[] = new AguardaRand($id);
}
// Iniciar a execucao das threads
foreach ($vetor as $thread) {
$thread->start();
}
// Encerrar o script
exit(0);
Pipe Example:
for ($i=0; $i<10; $i++) {
// abre 10 processos
for ($j=0; $j<10; $j++) {
$pipe[$j] = popen('script2.php', 'w');
}
// espera a finalização do processo
for ($j=0; $j<10; ++$j) {
pclose($pipe[$j]);
}
}