Guest User

Untitled

a guest
Aug 17th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. Clever way to share file data across threads in Perl
  2. #!/usr/bin/env perl
  3.  
  4. use strict;
  5. use warnings;
  6.  
  7. use threads;
  8. use Thread::Queue;
  9.  
  10. use constant MAX_THREADS => 5;
  11.  
  12. sub process_data
  13. {
  14. my( $q ) = @_;
  15. while( defined( my $data = $q->dequeue() ) )
  16. {
  17. print "Thread[".threads->tid()."]: Processing data($data)n";
  18. }
  19.  
  20. print "Thread[".threads->tid()."]: Got end messagen";
  21. } # END process_data
  22.  
  23. # Main program
  24. {
  25. my @threads;
  26. my $q = Thread::Queue->new();
  27. foreach ( 1 .. MAX_THREAD )
  28. {
  29. push( @threads, async { process_data($q) } );
  30. }
  31.  
  32. while( my $line = <STDIN> )
  33. {
  34. chop( $line );
  35. $q->enqueue( $line );
  36. }
  37.  
  38. foreach my $thread ( @threads )
  39. {
  40. $q->enqueue( undef );
  41. }
  42.  
  43. foreach my $thread ( @threads )
  44. {
  45. $thread->join();
  46. }
  47. }
  48.  
  49. use strict;
  50. use warnings;
  51. use Coro;
  52.  
  53. my $sem = Coro::Semaphore->new(10); # maximum of ten semaphores
  54. while my $line ( <$FILE> ) {
  55. $sem->down;
  56. async {
  57. dostuff($line);
  58. $sem->up;
  59. };
  60. }
Add Comment
Please, Sign In to add comment