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

Since threads of Perl has memory leak problem, I tried to use Coro. Is the following code correct? Thanks. Will async_pool be better?

use Coro; while (1) { async { &start_process(); } cede; //I found that without "cede;", start_process() will not run } sub start_process { ... }

Replies are listed 'Best First'.
Re: Use Coro for multi-threads, is this right?
by Corion (Patriarch) on Feb 24, 2010 at 07:44 UTC

    Coro implements cooperative multitasking/multithreading with explicit task switching, while threads implements scheduled multitasking/multithreading. If you don't know the difference, maybe Multithreading explains it in a different way.

    The advantage of Coro is that you don't get any race conditions. The advantage of threads is that you can get true parallelism across more than one CPU.

Re: Use Coro for multi-threads, is this right?
by ambrus (Abbot) on Feb 24, 2010 at 08:42 UTC

    When the main Coro ends, the program exits and the other Coros are abandonned. Wait for the other Coro at the end of the program if you want it to run to completion.

    For example, in this code the first loop will take more time than the second, but after the second one we wait for the first one to complete so the program doesn't exit. If you remove the join call, the program will exit early.

    use IO::Handle; use Coro; use Coro::Timer; my $s = async { for (0..11) { Coro::Timer::sleep 0.2; printflush STDOU +T "s"; } }; for (0..9) { Coro::Timer::sleep 0.1; printflush STDOUT "m"; } $s->join;

    Also, don't listen to Anon above, for Coro these days doesn't have so much bugs and memory leaks, provided you use a recent version of both Coro and the perl core itself.

Re: Use Coro for multi-threads, is this right?
by BrowserUk (Patriarch) on Feb 24, 2010 at 09:14 UTC

    Unless you've coded some cede points in your start_process() sub, you've coded a complicated serial loop.


    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: Use Coro for multi-threads, is this right?
by Anonymous Monk on Feb 24, 2010 at 07:12 UTC
    Coro probably has more leaks
      I heard that Coro is not thread, and is useless for CPU tense program. One Coro will wait for another Coro? How about async_pool?
Re: Use Coro for multi-threads, is this right?
by ikegami (Patriarch) on Feb 24, 2010 at 07:50 UTC

    If your premise is true, switching to Coro won't help since it uses threads to provide its functionality.

    Update: I must have been thinking of something else.