views:

121

answers:

4

I'm very curious in what multithreading is. I have heard the name battered around here and there in answers I have received on StackOverflow but I have no idea what it is, so my main two questions being what is it and how can I benefit from it?

EDIT:

Ok, since the first question didn't really get the response I was looking for I'll go with this..

I have never heard of 'threading' even in other languages. This is an example I have found on the internet:

#!/usr/bin/perl

use strict;
use warnings;
use threads;
use threads::shared;

print "Starting main program\n";

my @threads;
for ( my $count = 1; $count <= 10; $count++) {
        my $t = threads->new(\&sub1, $count);
        push(@threads,$t);
}
foreach (@threads) {
        my $num = $_->join;
        print "done with $num\n";
}
print "End of main program\n";

sub sub1 {
        my $num = shift;
        print "started thread $num\n";
        sleep $num;
        print "done with thread $num\n";
        return $num;
}

I cant seem to understand what it is that it is doing. Could anyone shine any light? Regards, Phil

A: 

http://perldoc.perl.org/Thread.html

Aaron
+1  A: 

It is like forking, but lighter weight and it is easier to share data between threads than between processes. The downside is that, because of the sharing of data, it is easier to write buggy code (thread a modifies something thread b thought should stay the same, thread a gets a lock on resource c and tries to get a lock on resource d, but thread b has a lock on resource d and is trying to get a lock on resource c, etc.).

Chas. Owens
A: 

It's when you have multiple threads.

siride
and could you tell me what a thread is?
Phil Jackson
+2  A: 

Threading is a way of having more than one thing happen at the same time, at least conceptually speaking (on a single-core single-CPU computer, perhaps with an ARM or Atom, there's only one thread of execution at a time).

The Perl example launches ten different sections of code simultaneously. Each chunk of code only has to take care of what it is doing, and doesn't have to worry about anything else. This means you can get the output of the Perl program with one simple subroutine called ten times in a reasonably simple fashion.

One use is in programs that interact with the user. It's typically necessary to have a responsive interface along with things happening behind the scenes. It's hard to do this in one lump of code, so often the interface will be in one thread and the behind-the-scenes stuff in other threads, so that the interface can be snappy and the background tasks running.

If you're familiar with running multiple processes, threads are very similar, although they're more closely connected. This means it's easier to set up and communicate between threads, but it's also easy to mess up by not allowing for all possible orders of execution.

David Thornley