From: Robert Klemme Date: 2004-08-12T00:01:14+09:00 Subject: Re: Thread takeover "Andre'" schrieb im Newsbeitrag news:opscknzpr3fqyrmb@orquidia... > Strangely, I'm having the problem that one thread is taking over the whole > process. > > Imagine this main file: > > Thread.new { > class Main > def initialize > while true > print 1 > end > end > end > m = Main.new > } > Thread.new { > require 'p.rb' > m = Main.new > } > while true; end Some remarks: - Thread#join is far better than "while true; end", because does not burn CPU resources. Apart from that the endless loop might behave bad with regard to thread scheduling - better define classes at top level - don't do processing in the constructor - don't use require for importing files that may change, require will only load once > It has two threads: one is printing 1 all the time in the screen. I have a > second - external - that is exactly like the first, but it prints 2. The > 'p.rb' is this one: > > class Main > def initialize > while true > print 2 > end > end > end > > It acts as expected. (11112222221111111222222) > > But if I add the line "m = Main.new" at the end of 'p.rb', the thread > seems to take over! (22222222222222222222222222222222222) That's probably a scoping issue; it might be that Main#initialize in p.rb overwrites Main#initialize in your script file. > Since this 'p.rb' is some external file the users will input, I can't tell > what it'll be on it, so I can't avoid that a malicious code takes over my > program! Or can I? You can't if you simply require arbitrary code. The interpreter will happily execute whatever he finds in p.rb. You can limit damage by setting $SAFE in the thread loading the code plus taking some more measures but I'm not sure whether you can really stop threads from running berserk. (I believe not.) Kind regards robert