ऐसे कई कारण हैं जिनसे आप बहुसंख्यक नहीं बनना चाहते हैं। यदि आप मल्टीथ्रेड करना चाहते हैं, हालांकि, निम्न कोड सहायक उदाहरण के रूप में कार्य कर सकता है। यह कई नौकरियां बनाता है, उन्हें थ्रेड-सुरक्षित कतार में रखता है, फिर कुछ थ्रेड शुरू करता है जो कतार से नौकरियां खींचते हैं और उन्हें पूरा करते हैं। प्रत्येक धागा एक लूप में कतार से नौकरियों को खींचता रहता है जब तक कि यह और अधिक नौकरियों को न देखे। कार्यक्रम सभी धागे को समाप्त करने के लिए इंतजार कर रहा है और फिर नौकरियों पर काम करने में कुल समय प्रिंट करता है।
#!/usr/bin/perl
use threads;
use Thread::Queue;
use Modern::Perl;
my $queue= Thread::Queue->new;
my $thread_count= 4;
my $job_count= 10;
my $start_time= time;
my $max_job_time= 10;
# Come up with some jobs and put them in a thread-safe queue. Each job
# is a string with an id and a number of seconds to sleep. Jobs consist
# of sleeping for the specified number of seconds.
my @jobs= map {"$_," . (int(rand $max_job_time) + 1)} (1 .. $job_count);
$queue->enqueue(@jobs);
# List the jobs
say "Jobs IDs: ", join(", ", map {(split /,/, $_)[0]} @jobs);
# Start the threads
my @threads= map {threads->create(sub {function($_)})} (1 .. $thread_count);
# Wait for all the threads to complete their work
$_->join for (@threads);
# We're all done
say "All done! Total time: ", time - $start_time;
# Here's what each thread does. Each thread starts, then fetches jobs
# from the job queue until there are no more jobs in the queue. Then,
# the thread exists.
sub function {
my $thread_id= shift;
my ($job, $job_id, $seconds);
while($job= $queue->dequeue_nb) {
($job_id, $seconds)= split /,/, $job;
say "Thread $thread_id starting on job $job_id ",
"(job will take $seconds seconds).";
sleep $seconds;
say "Thread $thread_id done with job $job_id.";
}
say "No more jobs for thread $thread_id; thread exiting.";
}
स्रोत
2009-09-26 18:06:43
कभी भी किसी भी चीज़ के लिए ithreads का उपयोग न करें। – jrockway
लिंक काम नहीं कर रहा है –