From this question , I came to the curiosity of wanting to learn more about the subject, then researching more deeply, I came across with more doubt on the subject. I've seen a string of ways to use Threads.
We can see the threads as small processes. The big difference from threads is that they share the same resources and memory addressing. That is, it is as if we have a process that is divided into smaller processes, where there is a switch between them, each one running a bit (as it happens in the processes), but now they share the same data and resources, work together. And I found it curious, since sometimes I had to catch enough to improve the performance of complex systems that are still very slow, and that they need to use sub systems to improve their performance.
Considering my case, in a future implementation, I would like to know what exactly changes between the three examples below, and when should I use one or the other and vise versa:
Fork example:
$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]);
}
}