I never do task's in ruby (without Rails). Now i need do to such thing:
Let's say i have 3 methods in ruby class:
a, b, c
in main method i need to execute method's via time, so that method run's not when i run script, but when time has come, for example:
a first must be executed in 11:59:30
then in xx-xx-xx, than in loop
a first must be executed in 12:00:30
then in xx-xx-xx, than in loop
etc
What i need to write, to google, or maybe give me simple example how can i do this?
can i do something like sleep until time == 14-50... ?
use sleep t to sleep t seconds.
for example a will run each t_a second. b in t_b and c in t_c seconds.
time = 0;
while true do
a if time % t_a == 0
b if time % t_b == 0
c if time % t_c == 0
time += 1
sleep 1
end
Related
How do I call .incr on a key and have it increment ONLY if the resulting number is < than a certain number without having to call .get beforehand?
The reason why is calling .get beforehand is problematic is because if I have multiple threads. There could possibly be 100 threads that have executed the first line below, they all get the value "0" and as a result, all increment. A race condition, if you will.
currentVal = $redis.get('key') #all threads could be done executing this but not yet the below if condition.
if(currentVal < 3)
$redis.incr('key') #1
end
You can either use WATCH/MULTI/EXEC semantics for optimistic locking, or compose a Lua such as this one (not tested):
local r=redis.call('GET', KEYS[1])
if r < ARGV[1] then
redis.call('INCR', KEYS[1])
end
I took the idea for lua script from Itamar Haber, improve it so it works, and added return values to know what happened on client side.
local r=redis.call('GET', KEYS[1])
if not r or tonumber(r) < tonumber(ARGV[1])
then
redis.call('INCR', KEYS[1])
return 1
else
return 0
end
I was wondering whether it's easy to make a race condition using MRI ruby(2.0.0) and some global variables, but as it turns out it's not that easy. It looks like it should fail at some point, but it doesn't and I've been running it for 10 minutes. This is the code I've been trying to achieve it:
def inc(*)
a = $x
a += 1
a *= 3000
a /= 3000
$x = a
end
THREADS = 10
COUNT = 5000
loop do
$x = 1
THREADS.times.map do Thread.new { COUNT.times(&method(:inc)) } end.each(&:join)
break puts "woo hoo!" if $x != THREADS * COUNT + 1
end
puts $x
Why am I not able to generate (or detect) the expected race condition, and get the output woo hoo! in Ruby MRI 2.0.0?
Your example does (almost instantly) work in 1.8.7.
The following variation does the trick for 1.9.3+:
def inc
a = $x + 1
# Just one microsecond
sleep 0.000001
$x = a
end
THREADS = 10
COUNT = 50
loop do
$x = 1
THREADS.times.map { Thread.new { COUNT.times { inc } } }.each(&:join)
break puts "woo hoo!" if $x != THREADS * COUNT + 1
puts "No problem this time."
end
puts $x
The sleep command is a strong hint to the interpreter that it can schedule another thread, so this is not a huge surprise.
Note if you replace the sleep with something that takes just as long or longer, e.g. b = a; 500.times { b *= 100 }, then there is no race condition detected in the above code. But take it further with b = a; 2500.times { b *= 100 }, or increase COUNT from 50 to 500, and the race condition is more reliably triggered.
The thread scheduling in Ruby 1.9.3 onwards (of course including 2.0.0) appears to be assigning CPU time in larger chunks than in 1.8.7. Opportunities to switch threads can be low in simple code, unless some kind of I/O waiting is involved.
It is even possible that the threads in the OP, each of which is performing just a few thousand calculations, are in essence occurring in series - although increasing the COUNT global to avoid this still does not trigger additional race conditions.
Generally MRI Ruby does not switch context between threads during atomic processes (e.g. during a Fixnum multiply or division) that occur within its C implementation. This means that the only opportunities for a thread context switch where all methods are calls to Ruby internals without I/O waiting, are "in-between" each line of code. In the original example, there are only 4 such fleeting opportunities, and it seems that in the scheme of things that this is not very much at all for MRI 1.9.3+ (in fact, see update below, these opportunities probably have been removed by Ruby)
When I/O waits or sleep are involved, it actually gets more complex, as Ruby MRI (1.9+) will allow a little bit of true parallel processing on multi-core CPUs. Although this is not the direct cause of race conditions with threads, it is more likely to result in them, as Ruby will usually make a thread context switch at the same time to take advantage of the parallelism.
Whilst I was researching this rough answer, I found an interesting link: Nobody understands the GIL (part 2 linked, as more relevant to this question)
Update: I suspect that the interpretter is optimising away some potential thread-switching points
in the Ruby source. Starting with my sleep version of the code, and setting:
COUNT = 500000
the following variation of inc does not seem to have a race condition affecting $x:
def inc
a = $x + 1
b = 0
b += 1
$x = a
end
However, these minor changes both trigger a race condition:
def inc
a = $x + 1
b = 0
b = b.send( :+, 1 )
$x = a
end
def inc
a = $x + 1
b = 0
b += '1'.to_i
$x = a
end
My interpretation is that the Ruby parser has optimised b += 1 to remove some of the
overhead of method despatch. One of the optimised-away steps is likely to include
the check for a possible switch to a waiting thread.
If that is the case, then the code in the question may never have the opportunity to switch threads within the inc method, because all the operations inside it can be optimised
in the same way.
I have the following code (from a Ruby tutorial):
require 'thread'
count1 = count2 = 0
difference = 0
counter = Thread.new do
loop do
count1 += 1
count2 += 1
end
end
spy = Thread.new do
loop do
difference += (count1 - count2).abs
end
end
sleep 1
puts "count1 : #{count1}"
puts "count2 : #{count2}"
puts "difference : #{difference}"
counter.join(2)
spy.join(2)
puts "count1 : #{count1}"
puts "count2 : #{count2}"
puts "difference : #{difference}"
It's an example for using Mutex.synchronize. On my computer, the results are quite different from the tutorial. After calling join, the counts are sometimes equal:
count1 : 5321211
count2 : 6812638
difference : 0
count1 : 27307724
count2 : 27307724
difference : 0
and sometimes not:
count1 : 4456390
count2 : 5981589
difference : 0
count1 : 25887977
count2 : 28204117
difference : 0
I don't understand how it is possible that the difference is still 0 even though the counts show very different numbers.
The add operation probably looks like this:
val = fetch_current(count1)
add 1 to val
store val back into count1
and something similar for count2. Ruby can switch execution between threads, so it might not finish writing to a variable, but when the CPU gets back to the thread, it should continue from the line where it was interrupted, right?
And there is still just one thread that is writing into the variable. How is it possible that, inside the loop do block, count2 += 1 is executed much more times?
Execution of
puts "count1 : #{count1}"
takes some time (although it may be short). It is not done in an instance. Therefore, it is not mysterious that the two consecutive lines:
puts "count1 : #{count1}"
puts "count2 : #{count2}"
are showing different counts. Simply, the counter thread went though some loop cycles and incremented the counts while the first puts was executed.
Similarly, when
difference += (count1 - count2).abs
is calculated, the counts may in principle increment while count1 is referenced before count2 is referenced. But there is no command executed within that time span, and I guess that the time it takes to refer to count1 is much shorter than the time it takes for the counter thread to go through another loop. Note that the operations done in the former is a proper subset of what is done in the latter. If the difference is significant enough, which means that counter thread had not gone through a loop cycle during the argument call for the - method, then count1 and count2 will appear as the same value.
A prediction will be that, if you put some expensive calculation after referencing count1 but before referencing count2, then difference will show up:
difference += (count1.tap{some_expensive_calculation} - count2).abs
# => larger `difference`
Here's the answer. I think you've made the assumption that the threads stop execution after join(2) returns.
This is not the case! The threads continue to run even though join(2) returns execution (temporarily) back to the main thread.
If you change your code to this you will see what happens:
...
counter.join(2)
spy.join(2)
counter.kill
spy.kill
puts "count1 : #{count1}"
puts "count2 : #{count2}"
puts "difference : #{difference}"
This seems to work a bit differently in ruby 1.8, where the threads do not seem to get a chance to run while the main thread is executing.
The tutorial is probably written for ruby 1.8, but the threading model has been changed since then in 1.9.
In fact it was pure "luck" that it worked in 1.8, as the threads do not finish execution when join(2) returns in neither 1.8 nor 1.9.
Lines 4 & 5 are causing me grief:
1 def test_break_statement
2 i = 1
3 result = 1
4 while true
5 break unless i <= 10
6 result = result * i
7 i += 1
8 end
9 assert_equal 3628800, result
10 end
I'm not sure what needs to remain true in the while true statement, however I believe it is the code that follows it. This leads to further confusion because I am reading the line:
break unless i <= 10 as break if i is not smaller or equal to 10. What procedure is this code going through ie how does the while and break statements interplay. I think I am nearly there but can't put the process in my head. Thanks.
The code will break out of the endless while loop when i is greater than 10.
But I'm not sure why the condition isn't checked in the while statement.
Edit: Had I read the method name I would have understood why the condition isn't checked directly with the while statement. The method's purpose is to test the break statement.
while statements test whatever comes after the word while. If the expression that follows them is true they execute the code within the loop. If the expression is false, they do not.
Thus, as other posters have pointed out, while true will always execute the code within the loop. Luckily for your code there is a break statement within the loop. If there wasn't, the loop would run forever and you'd have to kill the process running your program.
In your code sample the break keyword is followed by unless which means that it will break the loop unless the expression following it is true. Your code will break out of the loop when i is greater than 10.
while true is an infinite loop. break, when executed, will exit it immediately, to continue with the first line after it (assert_equal...).
In this specific case (nothing intervening between while and break unless), it is equivalent to this:
while i <= 10
result = result * i
i += 1
end
while true it is endless loop.
break unless i <= 10 is same as break if i > 10 it will break that loop if i is smaller or equal to 10
looper = (0..3).cycle
20.times { puts looper.next }
can I somehow find the next of 3? I mean if I can get .next of any particular element at any given time. Not just display loop that starts with the first element.
UPDATE
Of course I went though ruby doc before posting my question. But I did not find answer there ...
UPDATE2
input
looper = (0..max_cycle).cycle
max_cycle = variable that can be different every time the script runs
looper = variable that is always from interval (0..max_cycle) but the current value when the script starts could be any. It is based on Time.now.hour
output
I want to know .next value of looper at any time during the running time of the script
Your question is not very clear. Maybe you want something like this?
(current_value + 1) % (max_cycle + 1)
If, for example, max_cycle = 3 you will have the following output:
current_value returns
0 1
1 2
2 3
3 0
http://ruby-doc.org/core-1.9/classes/Enumerable.html#M003074