Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Concurrency

Status
Not open for further replies.

at02

Programmer
Jul 17, 2008
1
GB
I have two tasks: task1 and task2 that share a resource called Bert. I want to concurrently run both tasks. So that the resource Bert is shared. How do I go about this?
Can I do it with fork() or thread??? Any help or suggestion which be great.

Generally if someone knows how to program concurrency in perl I would love to know.
 
You'll need to be a little more specific on what the resource is. If task-1 & 2 are both simply reading from a file, minimal issues. If they're both reading and writing, that's a little trickier. If the resource is the hard drive, just let the OS take care of it.
 
I use threads in this case and I've always had good results (despite what some people seem to think about Perl's support for threads).

Here's a quick Windows example. Both methods will count simultaneously (instead of counting from 1 to 20 in succession):

#######################
use strict;

use threads;

my $thread = threads->create('countToTen'); # Create a thread...
countToTwenty(); # Keep going...

sub countToTen
{
for (my $i=1; $i<=10; $i++)
{
print "$i\n";
Win32::Sleep(500);
}
}

sub countToTwenty
{
for (my $i=11; $i<=20; $i++)
{
print "$i\n";
Win32::Sleep(500);
}
}
#######################

Note that if you need, you can use threads::shared and call the share() method to share a variable among both threads (very useful if you do any sort of GUI programming).



#!/usr/bin/perl
for(74,117,115,116,32,97,110,111,116,104,101,114,32,80,101,114,108,32,104,97,99,107,101,114,44){print(chr($_))}
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top