Skrevet av Emne: Perl: How to use threads  (Lest 2373 ganger)

ATC

  • Gjest
Perl: How to use threads
« på: 10. Juni 2009, 22:34 pm »
  • [applaud]0
  • [smite]0
  • How do I use threading and share data between the threads?



    ATC

    • Gjest
    [Solved] Perl: How to use threads
    « Svar #1 på: 10. Juni 2009, 22:34 pm »
  • [applaud]0
  • [smite]0
  • Approach 0
    Consider other, cleaner forms of paralellism: Client/server, forking, pre-forking and infinite state machines.


    Approach 1
    Use native Perl threads (or ithreads, as is the case with newer versions)
    Avoid shared variables unless you REALLY have to. Use queues instead.

    How:
    use threads;
    use Thread::Queue;

    Pros:
    Faster and more efficient than forking, especially when it comes to sharing variables.

    Cons:
    Modules that aren't marked thread-safe will most likely break.
    DBI is thread-safe but most DBD drivers are NOT.
    Specifically, DBD::mysql will fail even if you don't share anything.


    Approach 2
    Use the forks module to emulate real threads.
    Avoid shared variables unless you REALLY have to. Use queues instead.

    How:
    use forks;
    use Thread::Queue;

    Pros:
    Code as if you were using real threads, only you're not.
    Works even if perl was compiled without threads support.
    Modules work even if they're known to break with threads, because you're actually forking.

    Cons:
    Slight performance loss when sharing data because the data actually has to traverse a socket and the locking mechanism is not as efficient as it could have been. For any sane use the latency should be insignificant.