Skip to content

Instantly share code, notes, and snippets.

@mug896
Last active December 13, 2022 02:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mug896/1db1972c8ef8dd8abb44df8d9cb8d770 to your computer and use it in GitHub Desktop.
Save mug896/1db1972c8ef8dd8abb44df8d9cb8d770 to your computer and use it in GitHub Desktop.
#
# 다음은 thread 와 queue 를 활용하여 1 부터 1000 까지 prime 넘버를 구하는 예제입니다.
# 이것은 빠른 속도를 위한것은 아니고 thread 와 queue 를 이용해서 이렇게도 할 수 있다는 것을 보여주는 것입니다.
# prime 넘버가 하나 발견될 때마다 해당 prime 넘버용 thread 가 생성되고, 자신이 걸러내지 못하는 숫자는
# queue 를 이용해 downstream thread 로 보냅니다. 따라서 prime 넘버가 발견될수록 비례해서 thread 생성이 증가하고
# 그에따라 OS 단에서는 thread 간 context switching 이 증가하게 되는 구조가 됩니다.
# (1 부터 1,000 까지를 10,000 으로 변경해 실행을 해보면 점점 속도가 느려지는 것을 볼 수 있습니다.)
#
# bash$ ls /proc/`pgrep -x prime.pl`/task # 생성 스레드 조회
#
bash$ cat prime.pl
#!/usr/bin/perl
use strict;
use threads;
use Thread::Queue;
sub check_num {
my ($upstream, $cur_prime) = @_;
my $kid;
my $downstream = Thread::Queue->new();
while (my $num = $upstream->dequeue()) {
next unless ($num % $cur_prime);
if ($kid) {
$downstream->enqueue($num);
} else {
print("Found prime: $num\n");
$kid = threads->create(\&check_num, $downstream, $num);
if (! $kid) {
warn("Ran out of threads.\n");
last;
}
}
}
if ($kid) {
$downstream->enqueue(undef);
$kid->join();
}
}
my $stream = Thread::Queue->new(3..1000, undef);
check_num($stream, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment