MohammadReza Vahedi
MohammadReza Vahedi

Reputation: 729

force perl program to use all CPU capacity using threads

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?

Upvotes: 3

Views: 331

Answers (2)

robm
robm

Reputation: 1403

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.

Upvotes: 3

Fred Foo
Fred Foo

Reputation: 363807

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.

Upvotes: 4

Related Questions