use threads; use threads::shared; my $tcount :shared = 0; while(1){ if($tcount < 4){ print("Number of active threads : ".$tcount." processing incomming message\n"); threads->create(processData); } else { print("Maximum number of threads reached. Waiting \n"); sleep 1 until $tcount < 4; threads->create(processData); } } sub processData { $tcount++; #sleep(2); print "OK \n"; $tcount--; threads->exit(); }