Multi-threading is possible in php
Yes you can do multi-threading in PHP with pthreads
From the PHP documentation:
pthreads is an object-orientated API that provides all of the tools needed for multi-threading in PHP. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Threaded objects.
Warning:
The pthreads extension cannot be used in a web server environment. Threading in PHP should therefore remain to CLI-based applications only.
Simple Test
#!/usr/bin/php
<?php
class AsyncOperation extends Thread {
public function __construct($arg) {
$this->arg = $arg;
}
public function run() {
if ($this->arg) {
$sleep = mt_rand(1, 10);
printf('%s: %s -start -sleeps %d' . "\n", date("g:i:sa"), $this->arg, $sleep);
sleep($sleep);
printf('%s: %s -finish' . "\n", date("g:i:sa"), $this->arg);
}
}
}
// Create a array
$stack = array();
//Initiate Multiple Thread
foreach ( range("A", "D") as $i ) {
$stack[] = new AsyncOperation($i);
}
// Start The Threads
foreach ( $stack as $t ) {
$t->start();
}
?>
First Run
12:00:06pm: A -start -sleeps 5
12:00:06pm: B -start -sleeps 3
12:00:06pm: C -start -sleeps 10
12:00:06pm: D -start -sleeps 2
12:00:08pm: D -finish
12:00:09pm: B -finish
12:00:11pm: A -finish
12:00:16pm: C -finish
Second Run
12:01:36pm: A -start -sleeps 6
12:01:36pm: B -start -sleeps 1
12:01:36pm: C -start -sleeps 2
12:01:36pm: D -start -sleeps 1
12:01:37pm: B -finish
12:01:37pm: D -finish
12:01:38pm: C -finish
12:01:42pm: A -finish
Real World Example
error_reporting(E_ALL);
class AsyncWebRequest extends Thread {
public $url;
public $data;
public function __construct($url) {
$this->url = $url;
}
public function run() {
if (($url = $this->url)) {
/*
* If a large amount of data is being requested, you might want to
* fsockopen and read using usleep in between reads
*/
$this->data = file_get_contents($url);
} else
printf("Thread #%lu was not provided a URL\n", $this->getThreadId());
}
}
$t = microtime(true);
$g = new AsyncWebRequest(sprintf("http://www.google.com/?q=%s", rand() * 10));
/* starting synchronization */
if ($g->start()) {
printf("Request took %f seconds to start ", microtime(true) - $t);
while ( $g->isRunning() ) {
echo ".";
usleep(100);
}
if ($g->join()) {
printf(" and %f seconds to finish receiving %d bytes\n", microtime(true) - $t, strlen($g->data));
} else
printf(" and %f seconds to finish, request failed\n", microtime(true) - $t);
}
Create a function that you want the thread to execute, eg:
void task1(std::string msg)
{
std::cout << "task1 says: " << msg;
}
Now create the thread
object that will ultimately invoke the function above like so:
std::thread t1(task1, "Hello");
(You need to #include <thread>
to access the std::thread
class)
The constructor's arguments are the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.
If later on you want to wait for the thread to be done executing the function, call:
t1.join();
(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution).
The Code
#include <string>
#include <iostream>
#include <thread>
using namespace std;
// The function we want to execute on the new thread.
void task1(string msg)
{
cout << "task1 says: " << msg;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");
// Do other things...
// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
}
More information about std::thread here
- On GCC, compile with
-std=c++0x -pthread
.
- This should work for any operating-system, granted your compiler supports this (C++11) feature.
Best Answer
This is not specific to DbExpress (which I have no experience with), but the best idea for moving some functionality into a background thread is to first develop it in the main thread, debug it, and once you are sure it is performing fine, then move it.
What you can do is put everything onto a TDataModule. If the data module is able to work on its own, needing no other components on other forms or data modules, and you create it in the background thread, then you can be fairly certain that things will work. You don't need to clone the connection, as it will be created and destroyed in the same thread where all access to the database is performed.
Some important tips for database work with background threads:
Handle all exceptions, as unhandled exceptions in a secondary thread can / will crash your application. Exception handling in the Application object will not work for you.
Do not access anything in the GUI thread. That means most importantly that TDataSource is not usable, and no data sensitive controls can be used.
If the components you use do anything with SendMessage or PostMessage you will have to create a standard message loop in the background thread.
If the components you use do anything with OLE, call both OleInitialize() and OleUnitialize() in the context of the background thread.
If you want to make your life easier, consider using either OmniThreadLibrary or AsyncCalls. Which one depends on how long your background database connections will live and whether you want to reuse them.