in reply to Explicit thread context

I don't get it. Why are you forced to specify in advance the context that you'll be using? Does threads throw an assertion error if you accidentally use a different context than the one you promised you'd use?

⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

Replies are listed 'Best First'.
Re^2: Explicit thread context
by jdhedden (Deacon) on May 23, 2006 at 16:46 UTC
    Why are you forced to specify in advance the context that you'll be using?
    As threads execute asynchronously, the context must be set before the thread starts executing because it may call wantarray at any time during its execution, and may even finish before a ->join() call is made on it.

    Prior to threads v1.31, the context would be determined by how the ->create() call was made. This lead to the following counter-intuitive syntax if you wanted the threads object, but were expecting to get a list back from the thread:

    my ($thr) = threads->create('foo'); ... my @results = $thr->join();
    Additionally, this Perl bug has threads created in void context, but then tries to get return values from the thread.

    With threads 1.31, you can now specify the context directly so as to avoid such confusion:

    use threads 1.31; my $thr = threads->create({'list'=>1}, 'foo'); ... my @results = $thr->join(); threads->create({'context'=>'scalar'}, 'bar'); ... foreach my $thr (threads->list()) { my $rc = $thr->join(); }
    Does threads throw an assertion error if you accidentally use a different context than the one you promised you'd use?
    No, but you may not get the results you expect.

    Remember: There's always one more bug.
Re^2: Explicit thread context
by gellyfish (Monsignor) on May 23, 2006 at 15:50 UTC

    No, essentially it is so the the thread 'entry point' (the subroutine that forms the thread essentially) can have a different context than that of the create() which started the thread, that is to say you can tell it in advance what context the join() will be called in so that wantarray() will work properly, bearing in mind that the thread may already have checked wantarray to determine what to return before the context of the join is known.

    /J\

    A reply falls below the community's threshold of quality. You may see it by logging in.