라이브러리

[PHP] parallelChannel::open - 접근




PHP에서 parallel_channel::open은 PHP 8.1 버전부터 지원하는 기능으로, 병렬 처리를 위한 채널을 열어주는 함수입니다. 이 함수를 사용하면 PHP에서 병렬 처리를 쉽게 구현할 수 있습니다.

parallel_channel::open 함수의 사용법


parallel_channel::open 함수는 두 개의 인자를 받습니다. 첫 번째 인자는 채널 이름, 두 번째 인자는 옵션입니다.

#hostingforum.kr
php

use ParallelChannel;



$channel = Channel::open('my_channel');



예제 1: 간단한 병렬 처리


이 예제에서는 10개의 숫자를 5개의 스레드에서 처리하는 예제입니다.

#hostingforum.kr
php

use ParallelChannel;



$channel = Channel::open('my_channel');



$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];



$consumer = function ($number) {

    echo "처리 중: $number
";

    sleep(1);

    echo "처리 완료: $number
";

};



$producer = function ($number) use ($channel) {

    $channel->put($number);

};



$workers = [];

for ($i = 0; $i < 5; $i++) {

    $worker = new Worker($consumer);

    $worker->start();

    $workers[] = $worker;

}



foreach ($numbers as $number) {

    $producer($number);

}



foreach ($workers as $worker) {

    $worker->stop();

}



$channel->close();



예제 2: 채널에 데이터를 푸시하고 팝하는 예제


이 예제에서는 채널에 데이터를 푸시하고 팝하는 예제입니다.

#hostingforum.kr
php

use ParallelChannel;



$channel = Channel::open('my_channel');



$producer = function () use ($channel) {

    for ($i = 0; $i < 10; $i++) {

        $channel->put($i);

        echo "푸시: $i
";

        sleep(1);

    }

};



$consumer = function ($number) {

    echo "팝: $number
";

};



$producerWorker = new Worker($producer);

$producerWorker->start();



$consumerWorker = new Worker($consumer);

$consumerWorker->start();



$producerWorker->stop();

$consumerWorker->stop();



$channel->close();



예제 3: 채널에 데이터를 푸시하고 여러 개의 컨슈머가 팝하는 예제


이 예제에서는 채널에 데이터를 푸시하고 여러 개의 컨슈머가 팝하는 예제입니다.

#hostingforum.kr
php

use ParallelChannel;



$channel = Channel::open('my_channel');



$producer = function () use ($channel) {

    for ($i = 0; $i < 10; $i++) {

        $channel->put($i);

        echo "푸시: $i
";

        sleep(1);

    }

};



$consumer1 = function ($number) {

    echo "컨슈머 1 팝: $number
";

};



$consumer2 = function ($number) {

    echo "컨슈머 2 팝: $number
";

};



$producerWorker = new Worker($producer);

$producerWorker->start();



$consumer1Worker = new Worker($consumer1);

$consumer1Worker->start();



$consumer2Worker = new Worker($consumer2);

$consumer2Worker->start();



$producerWorker->stop();

$consumer1Worker->stop();

$consumer2Worker->stop();



$channel->close();



이 예제들은 PHP에서 병렬 처리를 위한 채널을 열어주는 `parallel_channel::open` 함수의 사용법을 보여줍니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 10,077건 / 347 페이지

검색

게시물 검색