asim-ishaq
asim-ishaq

Reputation: 2220

PHP pthreads memory issue

I am developing a networking application where I listen on a port and create a new socket and thread when a new connection request arrives; the architecture is working well but we are facing severe memory issues.

The problem is that even if I create a single thread, it does the work but the memory keeps on increasing.

To demonstrate the problem please review the following code where we start one thread of a class whose duty it to print a thread ID and a random number infinitely.

class ThreadWorker extends Thread {
    public function run() {
        while(1) {
            echo $this->getThreadId()." => ".rand(1,1000)."\r\n";
        }
    }
}

$th = new ThreadWorker();
$th->start();

I am developing it on Windows OS and when I open the task manager the PHP.exe memory usage keeps on increasing until the system becomes unresponsive.

Please note that the PHP script is executed from command line:

PHP.exe pthreads-test.php

Upvotes: 1

Views: 1368

Answers (1)

Claudi
Claudi

Reputation: 5416

OK, I think the problem is that the thread loop is highly CPU consuming. Avoid such that code. If you just want to echo a message, I recommend putting a sleep() instruction after. Example:

class ThreadWorker extends Thread {
    public function run() {
        while(1) {
            echo $this->getThreadId()." => ".rand(1,1000)."\r\n";
            sleep(1);
        }
    }
}

EDIT

It seems there's a way to force garbage collection in PHP. On the other hand, sleep() is not a proper way to stabilize CPU use. Normally threads do things like reading from files, sockets or pipes, i.e., they often perform I/O operations which are normally blocking (i.e. they pause the thread until data is I/O operation is possible). This behaviour inherently yields the CPU and other resources to other threads, thus stabilizing the whole system.

Upvotes: 1

Related Questions