Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Create a separate process with a sub...

by Foggy Bottoms (Monk)
on Aug 15, 2003 at 09:56 UTC ( [id://284111]=perlquestion: print w/replies, xml ) Need Help??

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

Hi, I'd like to run some code in parallel to other bits of code - the obvious answer was threads. However, I read that the thread package wasn't all that good and that it's best to turn to ithreads...

Unfortunately, I haven't found any help or examples on how to use ithreads... My main aim is to take a sub{} I've written and run separately from the rest of the code.

Could someone please show me how to do this ? All I've come across so far is Win32::Process which I reckon is for .exe files, not quite what I'd like.

Thanks for your input, David.
  • Comment on Create a separate process with a sub...

Replies are listed 'Best First'.
Re: Create a separate process with a sub...
by BrowserUk (Patriarch) on Aug 15, 2003 at 10:25 UTC

    Take a look at threads. If you are using AS, then the threads module is locate under the "Pragmas" section of the "Table of Contents" in the left-hand frame of the html docs.

    If all you want to do is run the sub standalone to completion, then that is as simple as

    use threads; sub YourSub { ... return $result; } ... my $thread = threads->new( \&YourSub, $arg1, $arg2, ... ); # If your not interested in the result from the sub then # $thread->detach; .... # Otherwise, this will retrieve the return value. # Note: This will block until the thread finishes. # One (of several) things missing from the API as it stands # is any way to determine if the thread has finished # without blocking. my $result = $thread->join;

    If you need to communicate between your main code and the subs whilst it is running, then life gets a little more complicated.

    If you give a clearer picture of what the sub is going to be doing (like the code:), then it may be possible to give a better example.


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
    If I understand your problem, I can solve it! Of course, the same can be said for you.

      # One (of several) things missing from the API as it stands
      # is any way to determine if the thread has finished 
      # without blocking.
      

      I think that's pretty easy to do with Thread::Exit.

      use threads (); use threads::shared (); my %exited : shared; use Thread::Exit end => sub { $exited{threads->tid} = 1 }; my $thread = threads->new( sub { whatever } ); my $tid = $thread->tid; while (!$exited{$tid}) { # do your stuff }
      Hmmm... maybe I should just add that to Thread::Exit... ;-)

      Liz

      Update:
      I worked a little on it ;-)

      The uploaded file
      
          Thread-Running-0.01.tar.gz
      
      has entered CPAN as
      
        file: $CPAN/authors/id/E/EL/ELIZABETH/Thread-Running-0.01.tar.gz
        size: 3963 bytes
         md5: 847d0175b6f5f355c97d20c73dce7311
      
      The POD starts with:
      NAME
             Thread::Running - provide non-blocking check whether threads are running
      
      SYNOPSIS
                 use Thread::Running;      # exports running(), exited() and tojoin()
                 use Thread::Running qw(running);   # only exports running()
                 use Thread::Running ();   # threads class methods only
      
                 my $thread = threads->new( sub { whatever } );
                 while (threads->running( $thread )) {
                 # do your stuff
                 }
      
                 $_->join foreach threads->tojoin;
      
                 until (threads->exited( $tid )) {
                 # do your stuff
                 }
      
      DESCRIPTION
      
             This module adds three features to threads that are sorely
             missed by some: you can check whether a thread is running,
             whether it can be joined or whether it has exited without
             waiting for that thread to be finished (non-blocking).
      
      For the impatient: it can also be fetched from my own list of CPAN modules.

        Neat! It would be nice if it added an is_finished() (or better named?) method to the threads package, but having an effective method of doing it is great.

        One comment on the name. I would probably never have considered using this without being recommended to it as I would have assumed (from the name) that it was designed for use with the old Thread package.

        I realise that using a "threads::" prefix is taboo as all lowercase names are reserved for pragmas, but maybe a "Threads" top level namespace is called for to distinguish between pThreads and iThreads stuff?

        Probably too late for that now. I'll just have to learn to look inside rather than making assumptions:)

        Now if only there was a portable way of making the Suspend/Resume/SetPriority/ thread (Win32 native) APIs available via threads objects. Most of this has analogous beaviour on other OS's, (priority ~= nice etc.), but it's probably a stretch to try and unify the api?


        Examine what is said, not who speaks.
        "Efficiency is intelligent laziness." -David Dunham
        "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
        If I understand your problem, I can solve it! Of course, the same can be said for you.

      Thanks again so much BrowserUk, your example is exactly what I needed...
      FYI, I'm accessing Outlook and I'm retrieving information. However, ever since Outlook 2000 SP2, a security window pops up : the aim of my thread is to monitor Windows and see whether that window pops up. The thread calls a sub which code is :
      sub clearSecurity { # As of Outlook 2000 SP2, MS has added a security component that preve +nts any code # run from accessing Outlook's inner properties. To impede that techni +cal protection # we need to clear the security popup window. my $securityHandle = 0; while (1) # keep on running the test { sleep(5); # sleep 5 seconds to wait for popup window to come up +(should there be one) $securityHandle = LTG::dialog::findSecurityWindow(); LTG::dialog::clearSecurityWindow($securityHandle) if ($securityH +andle); } }

      What I'm aiming at is to start the sub prior to fiddling with Outlook and kill right after having finished with Outlook...
        I need to run a thread that'll monitor the hard drive for any file changes

        Then maybe Win32::ChangeNotify is also worth a look.
        --
        bm

Re: Create a separate process with a sub...
by liz (Monsignor) on Aug 15, 2003 at 10:19 UTC
    I think that you will find perldoc perlthrtut helpful.

    I think what you want is the async() function.

    Liz

Re: Create a separate process with a sub...
by jdporter (Paladin) on Aug 15, 2003 at 12:02 UTC
    Maybe this is (a) too obvious, or (b) not acceptable for some reason... but,

    why don't you just fork? Given your criteria, that would be a simple and effective solution.

    jdporter
    The 6th Rule of Perl Club is -- There is no Rule #6.

      I thought fork() didn't work on Win32 systems ? I believe it's a Unix command only and not usable on WinNT, the OS I'm using...
        To my knowledge, fork() is emulated on Win32 systems using threads, thanks to the good work of Gurusamy Sarathy.

        Liz

        Contrary to poular myth, fork does work under win32 since at least 5.6. Under the covers it is implemented in exactly the same as threads are. IMO, the threads interface is easier to use than fork, but then I've never really made any great use of fork in C, so I'm coming from a different background.

        It also has the added bonus of making it reasonably easy to share data between parent and child.


        Examine what is said, not who speaks.
        "Efficiency is intelligent laziness." -David Dunham
        "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
        If I understand your problem, I can solve it! Of course, the same can be said for you.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://284111]
Approved by broquaint
Front-paged by broquaint
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2024-04-24 22:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found