mulithreaded server

Tim Roberts timr at probo.com
Thu Mar 13 03:02:33 EDT 2008


asit <lipun4u at gmail.com> wrote:
>
>In the above program, why there is an unhandeled exception ???

Probably because the code as you posted it has at least a half-dozen
mistakes.

>import socket
>import sys
>import thread
>
>p=1
>PORT=11000
>BUFSIZE=1024
>
>def getData(cSocket):
>    global stdoutlock,cSocketlock
>    while True:
>        cSocketlock.acquire()
>        data=cSocket.recv(BUFSIZE)
>        if data=='q':
>            data='client exited'
>            cSocket.close()
>            p=0
>            cSocketlock.release()
>        stdoutlock.acquire()
>        stdout.write(data)
>        stdoutlock.release()

You do not need the "global" statement there, since you are not changing
either stdoutlock or cSocketlock.  However, you ARE setting "p", so you
need a "global p".  Otherwise, you are simply creating a variable called
"p" that is local to the function, and which disappears when the function
returns.

Calling a global variable "p" is a very bad practice, by the way.

>def sendData(cSocket):
>    global stdoutlock,cSocketlock
>    while True:
>        stdoutlock.acquire()
>        data=raw_input('>>')
>        cSocketlock.acquire_lock()
>        if data=='q':
>            stdout.write('server exited')
>            stdout.release()
>            p=0
>            cSocket.close()
>        sSocket.send(data)
>        sSocketlock.release()

Same comments.  You do not need the "global" statement you have, but you do
need "global p" if you want to change the global version of "p".  Further,
as Jean-Paul pointed out and you rather rudely ignored, there is no
variable called "sSocketlock", because you commented it out.

Next, "stdout.release()" will fail.  "stdout" does not have a release
function.  You meant "stdoutlock.release()".

Next, you release sSocketlock, but you never acquired it.  And if data does
not equal "q", you repeatedly acquire stdoutlock, but you never release it.

Fix these problems, and then see if you can ask for help in a more thorough
fashion.
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list