- stretch 4.5.1-18.1
ns_thread(3aolserver) | AOLserver Built-In Commands | ns_thread(3aolserver) |
NAME¶
ns_thread - commandsSYNOPSIS¶
ns_thread begin scriptns_thread begindetached script
ns_thread get
ns_thread getid
ns_thread wait tid
ns_thread yield
DESCRIPTION¶
ns_thread begin:ns_thread begindetached:
ns_thread get:
ns_thread getid:
ns_thread wait:
ns_thread yield:
EXAMPLES¶
This example is similar to the example under the ns_sockselect function of connecting to the 10 servers and waiting to service them with the ns_sockselect command. In this case, though, each connection gets it's own thread.# This is the procedure which is evaluated for each thread and # handles a single connection to host number $i
proc getpage {i} { global pages # new thread will start here - first connect to host set host [format "www%2d.foo.com" $i] set fds [ns_sockopen $host 80 set r [lindex $fds 0] set w [lindex $fds 1] # next, send request puts $w "GET /index.htm HTTP/1.00r" flush $w # then read page set pages($i) [read $r] # and close sockets close $w close $r # thread goes away here and other threads waiting # on ns_thread wait will wakeup }
# Here's the loop which creates the threads which run getpage. for {set i 1} {$i < 9} {incr i} { set tids($i) [ns_thread begin "getpage $i"] }
# wait for the threads to exit and then process the pages for {set i 1} {$i < 9} {incr i} { ns_thread wait $tids($i) # output page ... process the page in $pages($i) put there by other thread ... }
Note that the code here is much simpler to follow than the ns_sockselect example; that's the benefit of multithreaded programming. However, it uses more resources as threads need to be created and initialized. This can be a problem if you plan to create many threads.
SEE ALSO¶
KEYWORDS¶
threads4.0 | AOLserver |