# Thread Question

**URL:** <https://www.ruby-forum.com/t/thread-question/84654>\
**Category:** Ruby\
**Created:** [February 6, 2007, 7:50pm UTC](https://www.ruby-forum.com/t/thread-question/84654 "2007-02-06T19:50:27Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dfg59](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e0b2c6/32.png) [@dfg59](https://www.ruby-forum.com/u/dfg59)\
**Post date:** [February 6, 2007, 7:50pm UTC](https://www.ruby-forum.com/t/thread-question/84654/1 "2007-02-06T19:50:27Z")

</div>

As posted earlier, I’m working on a simple chat server. However, I seem  
to be confused as to how I’m supposed to spawn a new thread. Let’s  
suppose I want to create a new Thread where an instance of Foo listens  
for messages on a socket and echos them. Is this correct? I have similar  
code in my server that I’m working on, but it is not functioning  
properly. It seems that my infinite while loops are blocking the rest of  
the code after the ‘#keep doing more stuff here’ section. Confusing…

mysocket = TCPSocket(‘[someaddress.com](http://someaddress.com)’,1000);  
Thread.new(mysocket){|socket| Foo.new(socket).listen}

# keep doing more stuff here

…  
…  
…

class Foo  
def initialize(socket)  
@socket = socket  
end

def listen  
while true  
message = socket.gets  
puts message  
end  
end  
end

---

<div class="post-metadata">

**Author:** ![dfg59](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e0b2c6/32.png) [@dfg59](https://www.ruby-forum.com/u/dfg59)\
**Post date:** [February 6, 2007, 10:05pm UTC](https://www.ruby-forum.com/t/thread-question/84654/2 "2007-02-06T22:05:13Z")

</div>

On Wed, Feb 07, 2007 at 03:50:35AM +0900, Drew O. wrote:

> # keep doing more stuff here

I think you forgot to call ‘accept’ in a loop, which returns a new  
socket  
for each connection, and then start a new thread for each one.

For a concrete, working example see  
[http://wiki.rubygarden.org/Ruby/page/show/SingletonTutorial](http://wiki.rubygarden.org/Ruby/page/show/SingletonTutorial)  
and scroll down to where it says “class Pop3Server”

For general information on threads see  
[http://www.rubycentral.com/book/tut\_threads.html](http://www.rubycentral.com/book/tut_threads.html)

HTH,

Brian.
