Re: RFC 178 (v1) Lightweight Threads

[email protected] (Steven W McDougall) Fri, 1 Sep 2000 15:52:12 -0400 (EDT)
Newsgroups perl.perl6.language.flow
Message-ID <[email protected]>
> KF>     #!/my/path/to/perl
> KF>     sub foo_generator { my $a = shift; sub { print $a++ } }
> KF>     my $foo = foo_generator(1);
> KF>     $foo->();
> Thread-> new($foo);

> KF> Is $a shared between threads or not? If $a is not shared, we've broken
> KF> lexicals.

> Not unless it is so declared	my $a :shared.

Sure it is.
Here are some more examples.


Example 1: Passing a reference to a block-scoped lexical into a thread.

    #!/my/path/to/perl
    foo();

    sub foo
    {
        my $a;
	Thread->new(\&bar, \$a)->join;
	$a++;
	print $a;
    }

    sub bar
    {
	my $a = shift;
	$$a++;
    }

Output: 2


Example 2: Declaring one subroutine within the scope of another

    #!/my/path/to/perl
    foo();

    sub foo
    {
        my $a;
	Thread->new(\&bar)->join;
	$a++;
	print $a;

	sub bar
	{
	    $$a++;
	}
    }

Output: 2


Example 3: Closures (Ken's example)

    #!/my/path/to/perl
    my $foo = foo_generator(1);
    $foo->();
    Thread->new($foo);

    sub foo_generator 
    { 
	my $a = shift; 
	sub { print $a++ } 
    }

Output: 12


- SWM