renodino has asked for the wisdom of the Perl Monks concerning the following question:

In Thread::Apartment, I have a run() method that is the sub provided to threads->create(), which provides the generalized dispatch of proxied methods of apt. threaded objects. In general it works fine.

However, I've encountered some odd behavior I hope someone can clarify (WinXP, AS 5.8.6). If I attempt to create a new apt. threaded object within an apt. threaded object, and Thread::Apartment's current thread pool is empty, a new thread is spawned via threads->create(\&run, ...args...). But when the new thread starts executing run(), it retains the values of lexically scoped variables declared inside the parent thread's run() instance.

Originally, I had an empty declaration:

my ($class, $tas, $req, $isa, $methods, $is_io, $is_tas, $tac);
Due to the logic of the proxied method dispatch loop, the fact that these variables "acquired" the values of the parent thread caused state issues inside the method dispatch loop.

When I changed the declaration to

my ($class, $tas, $req, $isa, $methods, $is_io, $is_tas, $tac) = (undef, undef, undef, undef, undef, undef, undef, undef);
everything worked fine.

Is this the intended behavior of threads ? Shouldn't lexically scoped variables be created within the local scope, and take undef as their default value, like any other (non-threaded) recursive call ?

Replies are listed 'Best First'.
Re: Threaded recursion and lexical variables
by dave_the_m (Monsignor) on Oct 17, 2005 at 21:21 UTC
    Shouldn't lexically scoped variables be created within the local scope, and take undef as their default value, like any other (non-threaded) recursive call ?
    Yes.

    Can you provide a short (say < 20 lines) but complete program that demonstrates this issue?

    Dave.