3

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?

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.