#!/usr/bin/perl use warnings; use strict; use 5.14.0; use threads; use threads::shared; use Time::HiRes qw(usleep); my @results = (); package Timer; sub new { my $classname = shift; my $self = {comparevalue => 0, limit => 100, timerstart => 5, state => "off", round => 0, stopthread => 0}; return bless($self, $classname); } sub startThread { my $self = shift; $self->{timer} = $self->{timerstart}; threads::shared::share($self->{timerstart}); threads::shared::share($self->{timer}); threads::shared::share($self->{comparevalue}); threads::shared::share($self->{limit}); threads::shared::share($self->{state}); threads::shared::share($self->{round}); threads::shared::share($self->{stopthread}); threads::shared::share(@results); $self->{thread} = threads->create(sub { $self->myThread() }); } sub myThread { my $self = shift; while ($self->{stopthread} == 0) { if ($self->{comparevalue} > $self->{limit}) { $self->{timer} = $self->{timerstart}; my $result = $self->runLoop(); push(@results, $result); } } } sub runLoop { my $self = shift; $self->{round}++; $self->{state} = "on"; while ($self->{timer} >= 0) { if ($self->{comparevalue} <= $self->{limit}) { $self->{state} = "off"; return 0; } Time::HiRes::usleep(100000); $self->{timer} -= 0.1; $self->{timer} = sprintf("%.1f", $self->{timer}); } $self->{state} = "off"; return 1; } sub getAktZeit { my $self = shift; return $self->{timer}; } sub getStatus { my $self = shift; return $self->{state}; } sub getRound { my $self = shift; return $self->{round}; } sub setCompareValue { my $self = shift; $self->{comparevalue} = shift; } sub stopThread { my $self = shift; $self->{stopthread} = 1; $self->{thread}->detach(); } package main; my $i = 0; my $timer = Timer->new(); $timer->startThread(); my $u; print "\$i\tTimerStatus\tTimerrestzeit\tTimerrunde\n"; for ($u = 0; $u <= 100; $u++) { $timer->setCompareValue($i); print "$i\t\t"; print $timer->getStatus() . "\t\t"; print $timer->getAktZeit() . "\t\t"; print $timer->getRound() . "\n"; Time::HiRes::usleep(200000); if ($u == 5 || $u == 40) { $i = 105; } if ($u == 20) { $i = 10; } } $timer->stopThread(); print "\nErgebnisse:\n"; print "Timerrunde\tErgebnis\n"; for $u (0 .. $#results) { print $u + 1; print "\t\t$results[$u]\n"; }