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

Hi there,

I have a perl-curses based script that essentially connects to a web-based ajax powered chatroom. This script simply allows me to use the chatroom from within my terminal, without needing a web browser. It works, however, I have a small issue.

It seems when a web request is made, the curses UI just freezes until the request is done. I figure I can solve this by making the web requests fork off into another thread.

I've tested the code and confirmed that it only happens while waiting for the webserver to respond.

However, I'm not sure about the easiest way to fix this. I'm using LWP for my web requests. Is there an easy way to make all the LWP HTTP requests thread and return back without having to rewrite a large portion of my code? Is there an easier way to solve the issue? Any advice would appreciated. :)

Replies are listed 'Best First'.
Re: Threading Web Requests with LWP
by BrowserUk (Patriarch) on Aug 20, 2014 at 10:00 UTC
    Is there an easy way to make all the LWP HTTP requests thread and return back without having to rewrite a large portion of my code?

    In theory, where you currently have something like:

    ... my $content; my $response = $ua->get('http://search.cpan.org/'); if ($response->is_success) { $content = $response->decoded_content; # or whatever } else { warn $response->status_line; } ...

    Simply add:

    use threads; ... my $content; my $thread = async{ my $response = $ua->get('http://search.cpan.org/'); if ($response->is_success) { return $response->decoded_content; # or whatever } else { return undef; } }; ... if( $thread->is_joinable() ) { $content = $thread->join; if( $content ) { #do domething with it } else { # notify the failure? } }

    It will probably end up being slightly more complex than that once you handle errors, but it shouldn't need to be much more so.

    If you post (the relevant part of) your code, I might be able to be a little more specific.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Threading Web Requests with LWP
by Anonymous Monk on Aug 20, 2014 at 09:28 UTC

    Proc::Background your lwpfetcher.pl

    In your curses gui check database (SQLite/DB_File/whatever) for new content