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

Hello. It seems that I can succeed at threading off a subroutine only if I do not check to see if I succeeded at it, which makes no sense. I have to be doing something wrong but I cannot see what. Can you?

I am running on Windows XP with Active State Perl v5.16.3) built for MSWin32-x86-multi-thread.

Here is a short bit of code, with the results after the __END__ statement

use 5.14.2; use threads; use Config; $Config{useithreads} or die('Recompile Perl with threads to run this program.'); ## sub endless_loop { my $button_answer = ""; my $count = 4; while (1) { while ($count--) { # Just wait around for a bit select(undef, undef, undef, 0.25); } say ("Main " . __LINE__); $count = 4; } } ## say "Main " . __LINE__ . ": Hello"; # Create and enter an endless loop in a different thread my $thread_endless_loop = threads->create(\&endless_loop) -> detach(); if (!($thread_endless_loop)) { my $message = "Main " . __LINE__ . ": Error"; die("$message Cannot create a thread\n$!\n"); } sleep(4); say "Main " . __LINE__ . ": Good Bye"; __END__ The (correct) results of running without the check for $thread_endless +_loop is: Main 25: Hello Main 19 Main 19 Main 19 Main 19 Main 35: Good Bye The results of running with the check for $thread_endless_loop is: Main 25: Hello Main 31: Error Cannot create a thread Inappropriate I/O control operation

Replies are listed 'Best First'.
Re: Threads works if not checked
by dave_the_m (Monsignor) on Jun 18, 2014 at 23:05 UTC
    You are setting $thread_endless_loop to the return value of the detach() method, which is not documented to return a value. Perhaps you meant:

    my $thread_endless_loop = threads->create(\&endless_loop); if (!($thread_endless_loop)) { my $message = "Main " . __LINE__ . ": Error"; die("$message Cannot create a thread\n"); } $thread_endless_loop->detach();
    Note also that $! will not have any meaningful value on failure to create a thread.

    Dave.

      Yes, that was it. Good eyes!