In script, I'm using threads and Thread::Queue and also using version perl 5.18.2. when I run my scripts it gives Error:This Perl not built to support threads In documentation, I read, it is an error. What is the possible solution to resolve this?
The forks module is a drop-in replacement for threads. It supports the same API, so the only change needed is to replace
use threads;
use threads::shared;
by
use forks;
use forks::shared;
You then use the same threading API, i.e. threads->create(\&worker) or something like that. The modules forks and forks::shared should be the first module you load. Note that forks has different performance characteristics from threads: Forking off a new process is cheaper than starting a thread (with the threads module), but communication between processes is more expensive than communication between threads.
Because forks is a drop-in replacement for threads, it works just fine with a Thread::Queue:
use forks;
use strict;
use warnings;
use feature 'say';
use Thread::Queue;
my $q = Thread::Queue->new;
my @workers = map { threads->create(\&worker, $q) } 1..3;
$q->enqueue(1..9);
$q->end;
$_->join for @workers;
sub worker {
my $q = shift;
my $tid = threads->tid;
while(defined(my $item = $q->dequeue)) {
say "$tid got $item";
sleep 1;
}
}
Example output:
1 got 1
2 got 2
3 got 3
1 got 4
2 got 5
3 got 6
1 got 7
2 got 8
3 got 9
When you build Perl, you need to use -Dusethreads to make a build of Perl that supports threads.
sh ./Configure -Dusethreads
make test
make install
I personally use perlbrew to install Perl.
perlbrew install 5.18.2 --as=5.18.2t -Dusethreads
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With