My code goes here - Threading a clock in Ruby. - Pastebin.com
I’m new to threading and also new to animations.
I’m trying to run a thread that prints out the time in (H:M:S) format.
Can you look at it and say something about it?
I want the clock to run on it’s own part of the screen without
interfering with my “what’s your name?” thing.
When I run the code this is what happens (and let’s think, for now I
type my name as “lol”)
Current time - 12:27:31
What’s your name?
Current time - 12:27:39ol #“ol” when i typed “lol”
lol is a nice name
Current time - 12:28:55
And yes, I’m new to “\r” carriage return too.
Hello,
you’re doing everything right. However, you’re outputting from two
threads to STDOUT, pure text, without any form of layout. So both
threads output their respective text to one file descriptor, interfering
with each other.
Just imagine what happens:
One thread outputs the clock, e.g. “12:35:32”. The \r causes the cursor
to move back to the beginning of the line. Then, the second thread asks
“what’s your name?”, with the cursor being on that line, overwriting the
initial output of the clock thread.
What you want to do is a little more complicated than just two threads:
You need some sort of windowing/layout mechanism. Probably something
along the lines of this would work (beware of subtile threading
issues!):
require 'ncursesw'
Ncurses.initscr
clock = Thread.new do
loop do
Ncurses.mvprintw 0, 0, "Current time: #{Time.now.strftime
"%I:%M:%S"}"
Ncurses.refresh
sleep 1.0
end
end
askname = Thread.new do
Ncurses.mvprintw 1, 0, "What's your name?"
name = gets.chomp
Ncurses.mvprintw 1, 20, "#{name} is a nice name!"
Ncurses.refresh
end
askname.join
clock.join
Ncurses.endscr
Hi, thanks for your answer. I’m new to threading so I don’t really
understand the codes so I’ll just research about the gem file you
required and read tutorials written for it. If you have some, please
post it, I would be grateful.
Thanks.