最近在網上和群里都看到很多朋友在討論php的多線程,也有說不能實現,也有人說沒必要,其實php用C語言寫出來,只要c能辦的,他基本都能辦到,所以就來寫了一個PHP多線程擴展,代碼也不多,也沒有考慮太多因素,只是簡單的創建線程和退出線程,為了防止創建線程過多對服務器性能造成影響,那么最大支持當前cpu個數X2個線程,如果要創建一個線程代碼如下:
$handle1 = mthread_create( 'text' , "hello fuction test\n" ); $handle2 = mthread_create( array (A, 'test' ), "hello A::test\n" ); while (1){ //mthread_exit($handle1);//可以使用mthread_create返回的句柄退出這個線程 sleep(1); } function test( $str ){ while (1){ echo $str ; sleep(1); } } class A{ function test( $str ) { echo $str ; sleep(1); } } |
原文轉自:http://blogread.cn/it/article/4495