use threads; use threads::shared; my $semaphore = new Thread::Semaphore; my $live_threads :shared = 0; my $thrwait_to_finish :shared = 5; my $maximum_active_threads :shared = 10; my @tid_array :shared; my @commands = ("show ip interface brief | exclude unassigned", "show vlan", "show vrf"); my @machines = ('1.1.1.1', '2.2.2.2', '3.3.3.3'); foreach my $cmd (@commands) { foreach my $machine_name (@machines) { my $url = "http://proxy:port/api/device/$machine_name/execute?cmd=$cmd"; if ($live_threads >= $maximum_active_threads) { my $new_thread_num = wait_for_finish(); $semaphore->down(); $live_threads = $new_thread_num; $semaphore->up(); } else { my $thread = threads->create('get_request', $cmd, $url, $machine_name); my $tid = $thread->tid(); $semaphore->down(); push (@tid_array, $tid); $live_threads++; $semaphore->up(); } } } sub get_request { sleep 1; my $cmd = $_[0]; my $url = $_[1]; my $machine_name = $_[2]; my $thread_id = threads->tid(); my $count = '0'; ... $web_response = $response->content; ... while ($thread_id != $tid_array[0]) { print "Thread_sleaping: $thread_id\n"; sleep 1; } ... $semaphore->down(); shift @tid_array; $semaphore->up(); print $fh ($webresponse); }