CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Need to implement threading concept

 



samir.gambler
New User

Nov 22, 2011, 2:41 AM

Post #1 of 3 (1832 views)
Need to implement threading concept Can't Post

I need to continuously monitor one directory for the creation of file. if the file is created in the directory i need to stop all the operation happening in my program and exit the program. Please help me in implementing this. I am new to threads concept of pearl.

Thanks.


samir.gambler
New User

Nov 22, 2011, 10:21 PM

Post #2 of 3 (1796 views)
Re: [samir.gambler] Need to implement threading concept [In reply to] Can't Post

I have tried to implement the case mentioned above but still i have some issue.


Code
use Thread qw(async);  
use threads::shared;

my $a :shared;
$a = 1;
$thr1 = async {
my $b;
{
lock ($a);
$b = $a;
}
while($b==1)
{
opendir (DIR, "C:\\temp");
my @filelist = grep (!/^\./, grep(-r, readdir(DIR)));
print ("file content is @filelist ");
close DIR;
exit "ERROR: file found!!\n" if (@filelist>0);
{
lock ($a);
$b = $a;
print ("Value of a is $a\n");
}
}
};


sleep (2);
{
lock ($a);
$a = 2;
print "\nSam EXP\n";
}
$thr1->join;



If any file is found in the directory then i am exiting..... till here it is ok. But if the file is not found in the directory and my rest of the program comes to an end then i want to stop the thread by changing the value of a shared variable $a, but it seems the new value of $a is not received by the thread. Can you please have a look at it and point out what I am doing wrong.
Thanks.


(This post was edited by samir.gambler on Nov 22, 2011, 10:23 PM)


histrung
Novice

Feb 1, 2012, 12:59 PM

Post #3 of 3 (1588 views)
Re: [samir.gambler] Need to implement threading concept [In reply to] Can't Post

Change

Code
# Bad 
use Thread qw(async);

to

Code
 # Good 
use threads qw(async);

Without this change it did exactly what you described. I have perl v5.8.8.8 and it worked for me.
Also, you should add a usleep to your checking thread, otherwise it will consume a large amount of CPU


Code
use Time::HiRes qw(usleep); 
# Sleep 0.00025 seconds or whatever you want
usleep(250);

Note:
(Prior to Perl 5.8, 5005threads was available through the Thread.pm API. This threading model has been deprecated, and was removed as of Perl 5.10.0.)


(This post was edited by histrung on Feb 1, 2012, 2:18 PM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives