Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Clever way to share file data across threads in Perl
- #!/usr/bin/env perl
- use strict;
- use warnings;
- use threads;
- use Thread::Queue;
- use constant MAX_THREADS => 5;
- sub process_data
- {
- my( $q ) = @_;
- while( defined( my $data = $q->dequeue() ) )
- {
- print "Thread[".threads->tid()."]: Processing data($data)n";
- }
- print "Thread[".threads->tid()."]: Got end messagen";
- } # END process_data
- # Main program
- {
- my @threads;
- my $q = Thread::Queue->new();
- foreach ( 1 .. MAX_THREAD )
- {
- push( @threads, async { process_data($q) } );
- }
- while( my $line = <STDIN> )
- {
- chop( $line );
- $q->enqueue( $line );
- }
- foreach my $thread ( @threads )
- {
- $q->enqueue( undef );
- }
- foreach my $thread ( @threads )
- {
- $thread->join();
- }
- }
- use strict;
- use warnings;
- use Coro;
- my $sem = Coro::Semaphore->new(10); # maximum of ten semaphores
- while my $line ( <$FILE> ) {
- $sem->down;
- async {
- dostuff($line);
- $sem->up;
- };
- }
Add Comment
Please, Sign In to add comment