From: Joshua Haberman Date: 2005-10-05T14:31:27+09:00 Subject: Re: state of blocking/nonblocking I/O On Oct 4, 2005, at 12:13 AM, David Gurba wrote: > Joshua Haberman wrote: >> while true >> (read_ready, write_ready, err) = IO.select([A, B, C]) >> read_ready.each { |io| >> output = process(io.read) >> [A, B, C].each { |client| client.write(output) unless >> client == io } >> } >> end >> >> Nonblocking I/O gives you more control over the execution of your >> program, and frees you from the worries of synchronizing between >> threads. And it's simpler than using threads for programs that >> follow certain patterns. >> >> Josh >> >> > This sounds really interesting, but I don't fully understand the > while loop. Nonblocking IO sends/recieves data when its ready/ > requested...eg. it doesn't block for the data, right? I'm not sure exactly what you're asking. Nonblocking I/O basically tells the OS: "when I do a read() or write(), only perform as much of the operation as you can without making me wait." If the OS cannot perform *any* of the operation (because there is no data waiting to read, or no buffer space available to write), the call errors with EAGAIN. IO.select is what you use to ask the OS what file descriptors are available for reading or writing. IO.select is what blocks, until one of your fds is available, or a timeout has elapsed. If you didn't use select, you'd have to busy-wait by reading from the fd over and over (getting EAGAIN every time). That would waste the CPU. Instead, you ask select to block until a file descriptor is available. > I have written some threaded applications. A java tic-tac-toe game > which had players and observers of a game that all viewed a global > 'board' state. Methods to modify the game state were thread safe > with mutexes, how is what your saying different...? Any info > appreciated... If you follow the pattern above, you don't have to make anything thread-safe. You don't have to use mutexes. You don't have to think about possibly bad interactions between threads like deadlock. Everything happens in the same thread. Josh