# Example: Event-Driven vs Thread I/O

- ## I/O bound apps are sometimes easier with threads:

global done count

proc my.read {sock} {

global done count

read $sock

if [eof $sock] {

close $sock

if {[incr count -1] == 0} {

set done 1

}

}

}

proc my.write {sock} {

puts $sock "GET /index.html\r\n"

flush $sock

fileevent $sock readable "my.read $sock"

}

set count 0

foreach host { host1 host2 host3 host4} {

incr count

set sock [socket -async $host 80]

fconfigure $sock -blocking off

fileevent $sock writable "my.write $sock"

}

vwait done

proc my.thread {host} {

set sock [socket $host 80]

puts $sock "GET /index.html\r\n"

flush $sock

read $sock

close $sock

}

foreach host {host1 host2 host3 host4} {

lappend tids [ns_thread begin ”my.thread $host"]

}

foreach tid $tids {

ns_thread wait $tid

}

Events

Threads

Previous slide | Next slide | Back to first slide | View graphic version