in reply to common modules and threads?
The general rule I see, is try and keep as much of your object code in the individual threads as is possible. So I think putting the require LWP in the thread code block is the obvious way to go. How would you share an LWP object across threads anyways? Unless they all were not utilizing the main object at the same time, or had some sort of queue.
Here is some code someone posted awhile back discussing the same thing. What you really are asking, is a question of the thread safety of the LWP module, which I have not seen questioned.... works well here. Never rely on the copy-on-write....you actually want to avoid it, because it causes thread safety problems.... like "free to wrong pool" errors.
You can "create" all your LWP objects in main, and pass them as parameters to the thread creation sub, but why have all that LWP code in main, if it's being used in the threads anyways? So do it as follows.
#!/usr/bin/perl use strict; use warnings; use LWP; use LWP::Simple; use threads; use Time::HiRes qw/gettimeofday/; sub HTTP_Req { my($tid,$host,$port,$uri)=@_; open my $FH, '>>', "test.csv" or die "$!"; my $req = new HTTP::Request 'POST'; my $url='http:' . '//' . $host . ':' . $port . $uri; my $ua = new LWP::UserAgent; $req->url($url); $req->header(Host => $host); $req->user_agent($ua->agent); $req->content_type('text/html'); my ($st_secs,$st_mins,$st_hours)=localtime(time); my ($seconds, $fraction) = gettimeofday(); $seconds = $seconds * 1000; my $st_ms = $fraction + $seconds; my $res = $ua->request($req); ($seconds, $fraction) = gettimeofday(); $seconds = $seconds * 1000; my $end_ms = $fraction + $seconds; my $resp_time=$end_ms - $st_ms; my ($end_secs,$end_mins,$end_hours)=localtime(time); my $resp_code=$res->code; if ($res->is_success) { print $FH "$tid,$st_hours:$st_mins:$st_secs,$end_hours:$end_mins:$end_secs,$st_m +s,$end_ms,$resp_time,$resp_code,SUCCESS\n"; } else { print $FH "$tid,$st_hours:$st_mins:$st_secs,$end_hours:$end_mins:$end_secs,$st_m +s,$end_ms,$resp_time,$resp_code,FAIL\n"; } close $FH; } my @threads; #my $host='domain.xyz.com'; my $host='http://google.com'; my $port='80'; my $uri='/'; my $threads=100; open my $FH, '>', "test.csv" or die "$!"; print $FH "tid,start_time,end_time,start Ms,End Ms,Response Time,ResponseCode,Result\n"; close $FH; for (1 .. 100) { my $thr = threads->create(\&HTTP_Req, $_,$host,$port,$uri); push(@threads,$thr); } $_->join foreach(@threads);
|
|---|