PHP က single thread လား multi thread လား ကိုယ်တိုင်စမ်းကြည့်ဖို့ code နမူနာများနှင့်ပြပါ
PHP သည် မူလအားဖြင့် single-threaded ဖြစ်ပါတယ်။ သို့သော် PHP 7.2 နှင့်အထက်မှာ parallel processing လုပ်နိုင်တဲ့ နည်းလမ်းအချို့ရှိပါတယ်။ ဒါပေမယ့် ဒါဟာ တကယ့် multi-threading မဟုတ်ပါဘူး။
နမူနာ code တွေနဲ့ ရှင်းပြပါမယ်:
- Single-threaded behavior ကို ပြသတဲ့ နမူနာ:
<?php
function longRunningTask() {
sleep(2);
echo "Task completed\n";
}
$start = microtime(true);
longRunningTask();
longRunningTask();
longRunningTask();
$end = microtime(true);
echo "Execution time: " . ($end - $start) . " seconds\n";
ဒီ code ကို run ရင် ခန့်မှန်းချေအားဖြင့် 6 စက္ကန့်ကြာမယ်။ ဘာကြောင့်လဲဆိုတော့ function တွေက တစ်ခုပြီးမှ တစ်ခု အစဉ်လိုက် run နေလို့ပါ။
- Parallel processing ကို simulate လုပ်ပြထားတဲ့ နမူနာ (PHP 7.2+):
<?php
function longRunningTask($id) {
sleep(2);
return "Task $id completed";
}
$start = microtime(true);
$pool = new \parallel\Runtime();
$future1 = $pool->run('longRunningTask', [1]);
$future2 = $pool->run('longRunningTask', [2]);
$future3 = $pool->run('longRunningTask', [3]);
echo $future1->value() . "\n";
echo $future2->value() . "\n";
echo $future3->value() . "\n";
$end = microtime(true);
echo "Execution time: " . ($end - $start) . " seconds\n";
ဒီ code က parallel extension သုံးထားပါတယ်။ ဒါကြောင့် tasks တွေက တပြိုင်နက်တည်း run နိုင်ပြီး၊ ခန့်မှန်းချေအားဖြင့် 2 စက္ကန့်လောက်ပဲ ကြာပါလိမ့်မယ်။
သတိပြုရမှာက ဒုတိယနမူနာက တကယ့် multi-threading မဟုတ်ပါဘူး။ ဒါဟာ parallel processing ကို simulate လုပ်ထားတာပါ။ PHP ရဲ့ core architecture က single-threaded ဖြစ်နေဆဲပါပဲ။