views:

228

answers:

4

I have a multithreded application in perl for which I have to rely on several non-thread safe modules, so I have been using fork()ed processes with kill() signals as a message passing interface.

The problem is that the signal handlers are a bit erratic (to say the least) and often end up with processes that get killed in inapropriate states.

Is there a better way to do this?

+1  A: 

From perl 5.8 onwards you should be looking at the core threads module. Have a look at http://search.cpan.org/~jdhedden/threads-1.71/threads.pm

If you want to use modules which aren't thread safe you can usually load them with a require and import inside the thread entry point.

Dave
+6  A: 

You can always have a pipe between parent and child to pass messages back and forth.

pipe my $reader, my $writer;
my $pid = fork();
if ( $pid == 0 ) {
    close $reader;
    ...
}
else {
    close $writer;
    my $msg_from_child = <$reader>;
    ....
}

Not a very comfortable way of programming, but it shouldn't be 'erratic'.

innaM
+7  A: 

Depending on exactly what your program needs to do, you might consider using POE, which is a Perl framework for multi-threaded applications with user-space threads. It's complex, but elegant and powerful and can help you avoid non-thread-safe modules by confining activity to a single Perl interpreter thread.

Helpful resources to get started:

Plus there are hundreds of pre-built POE components you can use to assemble into an application.

xdg
+4  A: 

Have a look at forks.pm, a "drop-in replacement for Perl threads using fork()" which makes for much more sensible memory usage (but don't use it on Win32). It will allow you to declare "shared" variables and then it automatically passes changes made to such variables between the processes (similar to how threads.pm does things).

tye