Asking for countdown while it's running - loops

I made a function with a while loop that countdown from a specific time and returns when Time is up.
But I want to make a function get_time() that tells me how much time is left on the timer while the other is running.
This second function is also a while loop that waits for my input to return where the countdown is at now.
So how can I make this get_time() function?

Look at the following code (python) as reference
from multiprocessing import Process
def func1():
print 'func1: starting'
for i in xrange(10000000): pass
print 'func1: finishing'
def get_time():
print 'get_time: starting'
for i in xrange(10000000): pass
print 'get_time: finishing'
if __name__ == '__main__':
p1 = Process(target=func1)
p1.start()
p2 = Process(target=get_time)
p2.start()
p1.join()
p2.join()

Related

Loop help (roblox)

I have a problem with this script:
local plight = script.Parent.Bulb.PointLight
local slight = script.Parent.Bulb.SpotLight
local rotatingPart = script.Parent.Bulb
local reader = script.Parent.Parent["card-reader1a"].reader1a.ProximityPrompt
local c = 0
local cc = 0
local tweenService = game:GetService("TweenService")
local tInfo = TweenInfo.new(0.5, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut, 0, false)
local function rotating()
if c == 0 then
c = 1
local play1 = tweenService:Create(rotatingPart, tInfo, {CFrame = rotatingPart.CFrame * CFrame.Angles(0, math.rad(120), 0)})
play1:Play()
play1.Completed:Connect(rotating)
c = 0
end
end
reader.Triggered:Connect(rotating)
I have infinitive loop and I don't know how to stop it. I tried many methods and nothing worked. Can someone help?
Try removing
play1.completed:Connect(rotating)
This line of code means that upon the tween's completion fire the rotating function. Effectively causing an infinite loop.
Additionally since :Connect() a signal doesn't yield, every time rotating is called, c is set from 1 to 0 almost instantaneously. Which allows all calls to pretty much bypass the debounce.
If you wish to wait until the tween is complete, try using
play1.completed:Wait()

How to perform actions periodically in Erlang

-define(INTERVAL, 1000).
init([]) ->
Timer = erlang:send_after(?INTERVAL, self(), tick),
{ok, Timer}.
handle_info(tick, OldTimer) ->
erlang:cancel_timer(OldTimer),
io:format("Tick ~w~n", [OldTimer]),
Timer = erlang:send_after(?INTERVAL, self(), tick).
{noreplay, Timer}.
start_clock() ->
{_, Timer} = init([]),
spawn(clock, handle_info, [tick, Timer]).
My codes is as above, but the output is not what I want.
How can I integrate init() and handle_info() into the main function(start_clock)?
In the timer module, the function apply_interval(Time, Module, Function, Arguments) executes Module:Function(Arguments) every interval of Time. It takes care of spawning a process, returns a reference to allow a cancellation later.
You also can have a look at send_interval(Time, Pid, Message) in the same library.
You can also implement a simple loop like:
loop(Args,Tick) when is_integer(Tick), Tick >= 0 ->
receive
stop -> stopped
after
Tick ->
do_something(Args),
{NewArgs,NewTick} = new_args(Args,Tick),
loop(NewArgs,NewTick)
end.
it is not a realtime timer, but the function new_args(Args,Tick) can help to correct the deviation due to process scheduling.
I think you need something like this:
start_timer() ->
gen_server:start_link({local, clock}, ?MODULE, [], []).

Using Parallel::ForkManager in foreach loop

I am just learning Perl as a fourth language.
My wish is to use Parallel::ForkManager to speed up a foreach loop using an array whose members are taken from a text file.
Basically I am testing a .txt file of URLs, and wish to make it so that it will test multiple members of the array at once, not one at a time (five at a time in this instance) and without spamming the same URL inadvertently DoSing it.
Would something like this do the trick?
$limit = new Parallel::ForkManager(5);
foreach (#lines) {
$limit->start and next;
$lines = $_;
... do processing here ...
$limit->finish;
}
or would it be the equivalent of running that loop 5 times making a small multithreaded DoS script?
It isn't too clear from the documentation, but
A call to start will block in the parent process until there are fewer children running than the limit specified. Then it will return the (non-zero) child PID in the parent, and zero in the child
A child process can see all the data in the parent process as it was when the start was called. The data is presumably copy-on-write, as the child may modify it but the changes aren't reflected in any other process's workspace
The $pm->start and next idiom may seem a little obscure. Essentially it skips the rest of the loop if the start method returns a true value. I prefer something like my $pid = $fm->start; next if $pid; or the if construct in the code below. Both do the same thing, but I think more legibly
I recommend that you experiment with this simpler application, which uses a cache of five child threads to print the numbers from zero to nine.
use strict;
use warnings;
use Parallel::ForkManager;
STDOUT->autoflush;
my $fm = Parallel::ForkManager->new(5);
for my $i (0 .. 9) {
my $pid = $fm->start;
if ($pid == 0) {
print "$i\n";
sleep 2;
$fm->finish;
}
}
To test, use a safe local process like print or write to avoid spamming the URL's. Here's a working snippet from a program I wrote that uses the fork manager.
my $pm=new Parallel::ForkManager(20);
foreach $add (#adds){
$pm->start and next;
#if email is invalid move on
if (!defined(Email::Valid::Loose->address($add))){
writeaddr(*BADADDR, $add); #address is bad
$pm->finish;
}
#if email is valid get domain name
$is_valid = Email::Valid::Loose->address($add);
if ($is_valid =~ m/\#(.*)$/) {
$host = $1;
}
$is_valid="";
# perform dsn lookup to check domain
#mx=mx($resolver, $host);
if (#mx) {
writeaddr(*GOODADDR, $add); #address is good
}else{
writeaddr(*BADADDR, $add); #address is bad
}
$pm->finish;
}

Matlab, timed iteration over a matrix

I'm developing a simulator of sorts as a hobby project. The specific function i'm having trouble with takes a row from a matrix and supplies to a function every 50'th millisecond, but I'm a novice with Matlab scripting and need some help.
Each time the timer clicks, the next row in the matrix should be supplied to the function "simulate_datapoint()". Simulate_datapoint() takes the row, performs some calculation magic and updates a complex "track" object in the tracks array.
Is this a completely backwards way of trying to solve this problem or am I close to a working solution? Any help would be greatly appreciated.
Here's what I have right now that doesn't work:
function simulate_data(data)
if ~ismatrix(data)
error('Input must be a matrix.')
end
tracks = tracks_init(); % create an array of 64 Track objects.
data_size = size(data,1); % number of rows in data.
i = 0;
running = 1;
t = timer('StartDelay', 1, 'Period', 0.05, 'TasksToExecute', data_size, ...
'ExecutionMode', 'fixedRate');
t.StopFcn = 'running = 0;';
t.TimerFcn = 'i = i+1; simulate_datapoint(tracks, data(i,:));';
disp('Starting timer.')
start(t);
while(running==1)
% do nothing, wait for timer to finish.
end
delete(t);
disp('Execution complete.')
end
You're very close to a working prototype. A few notes.
1) Your string specified MATLAB functions for the timerFn and stopFn don't share the same memory address, so the variable "i" is meaningless and not shared across them
2) Use waitfor(myTimer) to wait... for the timer.
The following code should get you started, where I used "nested functions" which do share scope with the calling function, so they know about and share variables with the calling scope:
function simulate
iterCount = 0;
running = true;
t = timer('StartDelay', 1, 'Period', 0.05, 'TasksToExecute', 10, ...
'ExecutionMode', 'fixedRate');
t.StopFcn = #(source,event)myStopFn;
t.TimerFcn = #(source,event)myTimerFn;
disp('Starting timer.')
start(t);
waitfor(t);
delete(t);
disp('Execution complete.')
% These are NESTED functions, they have access to variables in the
% calling function's (simulate's) scope, like "iterCount"
% See: http://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html
function myStopFn
running = false;
end
function myTimerFn
iterCount = iterCount + 1;
disp(iterCount);
end
end

Function of Ruby's Thread#join(0)?

So, we're trying to debug a problem with an app of ours and we think we've narrowed it down to a threading issue.
I understand based on Ruby's documentation on Thread that providing an integer argument to the join method specifies how long it will wait for the thread to join up before just returning nil.
However, I'm not sure what happens when you pass in '0.'
One of my colleagues, after digging around in the C code for the Ruby interpreter, seems to think that it's not "don't wait at all just join it immediately and return nil if it doesn't come back" and is more along the lines of "don't bother joining and just return a snapshot of the thread at the given moment."
Can anyone point me to some documentation on (or just flat out tell me) what passing a '0' argument to join() does?
After testing the code by Diego Basch:
def f()
y = Thread.new { 4.times { sleep 0.1; puts 'tick... ' }}
puts "Waiting" until y.join(0)
end
def g()
y = Thread.new { 4.times { sleep 0.1; puts 'tick... ' }}
puts "Waiting" until y.join(0.0000000000001)
end
def h()
y = Thread.new { 4.times { sleep 0.1; puts 'tick... ' }}
puts "Waiting" until y.join(0.15)
end
f and g are very similar.
The reason for this is that f is just the limit -- put in as small of a number as possible.
And they mean the same thing. Check virtually immediately to see if the thread is done. When it isn't, return nil.
Thus in the code above, the until repeatedly evaluates in the first 2 cases but only evaluates a couple of times in the third case (in particular, every 0.15 seconds). Using 0 as a parameter functions exactly like every other number -- check to see if the thread is done in the next 0 seconds (now) and if it isn't return nil.
I'm afraid your colleague is not correct.
Your colleague is correct. Try this code for example:
y = Thread.new { 4.times { sleep 0.1; puts 'tick... ' }}
puts "Waiting" until y.join(0)
and compare with:
y = Thread.new { 4.times { sleep 0.1; puts 'tick... ' }}
puts "Waiting" until y.join(0.15)
See the documentation for join

Resources