11

perldoc threads says:

The use of interpreter-based threads in perl is officially discouraged.

Are there any other Perl based threads? Or should we just not use threads in Perl?

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
ealeon
  • 12,074
  • 24
  • 92
  • 173

3 Answers3

11

Depends on what you're trying to accomplish. I still use threads extensively, and there isn't a massive problem with them.

The biggest problem with them is that they are not lightweight, where if you've threaded in other languages, you might expect them to be.

They're more the opposite - spawning a thread is like starting your code again, but with some useful hooks for IPC. That means you really don't want to be doing a task-per-thread model of program, like you might be thinking of.

Instead, you would be much better served by a Thread::Queue worker-thread style model. Here's an example of that: Perl daemonize with child daemons

However, you may want to consider using fork as an alternative. fork - because of it's implementation on Unix - is a very efficient system call, and can be quite efficient for spawning new processes. The downside is - it's not quite as friendly for doing IPC.

Parallel::ForkManager is one module that I like for doing forking for multiprocessing.

But in either case you should note - multiprocessing isn't a magic bullet. It lets you hog more CPUs if you have the right sort of problem to solve. It won't make your disks go any faster :)

Community
  • 1
  • 1
Sobrique
  • 52,974
  • 7
  • 60
  • 101
7

That warning is poppycock. It should be removed. The developers of Perl explained that it means "The use of interpreter-based threads in perl is officially discouraged if you want a lightweight system for multitasking".

Since creating new threads can be expensive, just use a model that involves reusable worker threads.

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • 2
    Indeed. The biggest "flaw" I've found is the assumption that they're lightweight, like they are in some other languages. – Sobrique May 05 '15 at 15:53
1

As long as I know, there are not any reliable thread implemantations. You should stick to some event-based modules, like Coro, AnyEvent, IO::Async etc.

Vadim Pushtaev
  • 2,332
  • 18
  • 32
  • 7
    Just cause the docs aren't clear, Coro is a co-operative multi-tasking system. If you want to use threads to split CPU load across cores, it's not going to help. Any neither are event-based systems. They're useful when most tasks are spent waiting on external events. – ikegami May 05 '15 at 15:20
  • 6
    Perl threads are perfectly reliable. They're just not a _light weight_ thread that you might expect if you've come from another language. – Sobrique May 05 '15 at 15:52
  • Alas, Coro and AnyEvent are not supported since perl 5.22. – Sue D. Nymme Jan 26 '22 at 14:21