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

Is there a way to have your threads (yeah, I know, yet another reason to use fork()) get and set their own environment and then throw it away (eg so that other threads don't get in the way while sleep() ing or doing something useful)? eg:
sub doSomethingStupid { $ENV{TIME} = shift; sleep($ENV{TIME}); print "Time is $ENV{TIME}"; } @vars = ("1", "2", "3", "1"); foreach $var (@vars) { my $thread = new Thread \&doSomethingStupid ($var); $thread->detach(); }

Replies are listed 'Best First'.
Re: $ENV for Threads?
by Dog and Pony (Priest) on Apr 09, 2002 at 09:51 UTC
    I don't think so.

    Well, yes, I know anything is possible, especially in perl. But when you are using threads, you are still within the same program, and within the scope of the same program. When it comes to global data, think of the thread as any ordinary sub routine. If you change %ENV from the sub routine, it will change for the whole program no matter if it is a threaded sub or not.

    The only difference is that you can change it in several places simultaneously if you are not careful. :)


    You have moved into a dark place.
    It is pitch black. You are likely to be eaten by a grue.
Re: $ENV for Threads?
by perlplexer (Hermit) on Apr 09, 2002 at 13:14 UTC
    Have you tried doing this ?
    sub thread{ local %ENV = %ENV; # ... code ... }

    --perlplexer
      That would be... very bad. Don't do it.

      The local localizes a global, but doesn't make it thread-local, so you'll be changing thigns for everyone. (And without locking either, which will definitely Do Bad Things)

      There's no good way which actually uses %ENV. Best thing to do is to either wrap access in an interface of some sort, or copy %ENV to a different hash.

      If you actually need a thread-locak version of %ENV because you're using code you didn't write, well... you're out of luck.