Limited Offer
60% OFF on all plans!

Concurrency & Delay in PHP

Explore concurrency patterns in PHP using sleep(), pcntl_fork(), ReactPHP, and Swoole for handling parallel and asynchronous tasks.

PHP Concurrency Model

Traditional PHP is synchronous and single-threaded per request — one request runs one script from top to bottom. Concurrency in PHP is achieved at the process or extension level, not via an event loop like Node.js.

1. Synchronous Execution Model

PHP runs one line at a time — blocking by default.

2. Concurrency Approaches in PHP

Overview of available strategies.

Delays — sleep() & usleep()

PHP provides `sleep()` and `usleep()` for blocking delays. These are useful in retry logic, rate limiting, and polling loops.

1. sleep() — Second-Level Delay

Block execution for N whole seconds.

2. usleep() — Microsecond Delay

Fine-grained sub-second pauses.

3. Retry with Exponential Backoff

Practical pattern using sleep().

Parallel Processes

PHP can spawn child processes using `pcntl_fork()` (Unix) or `proc_open()` (cross-platform), enabling true parallel execution.

1. proc_open() — Spawn Child Processes

Run external commands in parallel.

2. pcntl_fork() — Fork Processes (Unix)

Duplicate the current process for parallel work.

Parallel HTTP Requests

The `curl_multi_*` functions let you issue multiple HTTP requests in parallel and collect all responses — much faster than sequential requests.

1. curl_multi_exec() — Parallel cURL

Fire multiple requests at once.

Fibers — Cooperative Multitasking (PHP 8.1+)

Fibers (PHP 8.1) are lightweight coroutines that can pause mid-execution and resume later. They are the foundation for async frameworks in modern PHP.

1. Creating and Running a Fiber

Fiber::suspend() pauses; resume() continues.

2. Passing Data In and Out

suspend() returns a value; resume() sends one.

3. Fiber Status Methods

Check fiber lifecycle state.

Async Frameworks Overview

For production async PHP, libraries like ReactPHP and the Swoole extension provide event loops, async I/O, and non-blocking primitives.

1. ReactPHP — Event Loop

Non-blocking I/O via an event loop.

2. Swoole — Async PHP Extension

C-level coroutines and async I/O built into PHP.