简体   繁体   中英

Multi-Threading in Perl vs Java

I am new to Perl and I am writing a program that requires the use of threading. I have found the threads feature in Perl, but I find that I am still a bit confused. As stated in the title of this post Java is probably the most common to use threads. I am not saying that it is perfect, but I can get the job done using the Thread class.

In Java I have a method called startThreads and in that method I created the threads and then started them. After starting them there is a while loop that is checking if the treads are done. If all the threads have exited properly then the while loop exits, but if not then the while loop is watching what threads have timed out and then safely interrupts those threads and sets their shutdown flags to true.

The problem: In Perl I want to use the same algorithm that I have stated above, but of course there are differences in Perl and I am new to Perl. Is it possible to have the while loop running while the other threads are running? How is it done?

You can implement your while loop in Perl using threads->list() but you should consider a different approach, first.

Instead of waiting for threads, how about waiting for results?

The basic idea here is that you have code which takes work units from a queue and which puts the results of the work units (either objects or exceptions) into a output queue.

Start a couple of threads that wait for work units in the input queue. when one show up, run the work unit and put the result in the output queue.

In your main code, you just need to put all the N work units into the input queue (make sure it's large enough). After that, you can wait for N outputs in the output queue and you're done without needing to worry about threads, joins and exceptions.

[EDIT] All your questions should be answered in http://perldoc.perl.org/perlthrtut.html

Be careful when using threads in perl. There are a lot of nuances about safely accessing shared data. Because most Perl code does not do threading, very few modules are thread-safe.

After reading the link that Michael Slade provided, I found that Cyber-Guard Enterprise was correct. By detaching the thread the main still is performing work. I haven't tested it out yet, but it looks like $thr->is_running() can tell me if the thread is still running.

This was taken from the url that was provided and shows how detach is used. perldoc.perl.org/perlthrtut.html?

use threads;
my $thr = threads->create(\&sub1); # Spawn the thread
$thr->detach(); # Now we officially don't care any more
sleep(15); # Let thread run for awhile
sub sub1 {
$a = 0;
while (1) {
$a++;
print("\$a is $a\n");
sleep(1);
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM