Question

I have a laptop with a CPU Intel Core i3 and I want to create a simple program in Perl to use 100% of CPU capacity. I have read about Threads and search about running them parallel but I can't use 100% of the CPU.

my code:

use strict;
use warnings;
use threads;
use threads::shared;
print "Starting main program\n";

my $t1 = threads->create(\&sub1, 1);
my $t2 = threads->create(\&sub1, 2);
my $t3 = threads->create(\&sub1, 3);
my $t4 = threads->create(\&sub1, 4);

$t1->join();
$t2->join();
$t3->join();
$t4->join();
print "End of main program\n";
sub sub1 {
my $num = 20;

print "started thread $num\n";
sleep $num;
print "done with thread $num\n";
return $num;
}

but after running CPU usage is about 10%.

How do I use 100% of the CPU?

Was it helpful?

Solution

You need to make the threads actually do something. E.g. make them count from 0 to a large number. Sleeping doesn't take CPU time.

OTHER TIPS

You're not using any CPU because the threads are sleeping - which tells the OS basically "I'm not doing anything, so use your resources elsewhere".

try some computation - like a nested loop with divisions and printing the result to /dev/null instead of sleeping.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top