Perl Multithreading: ''forks'' vs ''threads'' in cross platforms scripts

Viewed 580

I'm trying to develop a software featuring multithreading. On Linux the script works fine, the module i've used is ''forks''. In other words, no problem of shared handlers between threads while querying db and stuff like that. Once i've been trying to run the script on windows (Strawberry Perl), when i try to cpan install forks it says that ''forks module'' is not supported for the current version of my OS (64bit). Moving over, i decided to use ''threads'' instead, but i gained the following error, almost certainly linked with shared handlers between threads.

'' Thread 1 terminated abnormally: DBD::SQLite::db prepare failed: handle 2 is owned by thread d97fe8 not current thread 3a01058 (handles can't be shared between threads and your driver may need a CLONE method added) at file.pl line 180, line 1. ''

How to fix the aforementioned problem and make the script runnable on windows Strawberry Perl?

2 Answers

First of all, thanks everybody for the prompt answer and the very good suggestions. That's my solution. Apparently, it seems there's no need to create a new db handler for each thread, just connect to the database each and every time you create a new thread. So, if you're using ''threads'', i think it should be enough to include the following line within the ''threads->create'' method to make it runnable:

$dbh = DBI->connect( "dbi:SQLite:db_name.dbl" ) || die "Cannot connect: $DBI::errstr";  

As you can see, the handler is static but it's not literally ''shared'' between threads, as it is created each and every time you connect to the db, so each and every time you run a new thread!

Please, don't ask me why the original script works fine in Linux using ''forks'' and without this trick...it seems that with ''forks'' you don't need to care about shared handlers.

Thanks again

Related