VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • python实战--Http代理服务器(2)

其实Http代理服务器本身不难,但写出来还是挺费事的,这里就不细说源代码了,很简单。主要说说,我遇到的问题。

一: 我本来只知道,thread.start_new_thread的第一个参数是函数对象,但当我看到上面的博文时,心里一愣,这样也可以,于是我迅速的测试了一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import thread
  
class Hello:
    def __init__(self,content):
        print content
  
def cs():
        thread.start_new_thread(Hello, ("Hello World",))
  
if __name__=='__main__':
    cs()
import thread
class Hello:
    def __init__(self,content):
        print content
def cs():
        thread.start_new_thread(Hello, ("Hello World",))
if __name__=='__main__':
    cs()

Unhandled exception in thread started by  
Error in sys.excepthook: 

Original exception was:

Unhandled exception in thread started by
Error in sys.excepthook:

Original exception was:

一看,我说嘛,第一个参数怎么可以是对象,我呵呵一笑,稍微鄙视了一下作者。于是,我洗洗睡了,第二天,我还是不死心,于是把代码下下来,本地实验了一下,可以的,立马意识到是我2了,于是立马百度。

原来thread模块中,主线程如果比子线程先结束,就会抛出这个异常,所以我们必须让子线程先结束,最简单的方法就是让主线程sleep足够长的时间,至于多长时间,貌似不知道,那到底怎么解决呢?

比较好的解决办法就是,主线程给每个子线程都加一把锁,子线程在结束前将锁释放掉,主线程一直循环检查锁的状态。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import thread
  
class Hello:
    def __init__(self,content,lock):
        print content
        """
        do something
        ....
        At the end,release the lock
        """
        lock.release()
  
def cs():
        lock=thread.allocate_lock()
        lock.acquire()
        thread.start_new_thread(Hello, ("Hello World",lock))
        while True:
            if not lock.locked():
                break
        print "lock release"
  
if __name__=='__main__':
    cs()
import thread
class Hello:
    def __init__(self,content,lock):
        print content
        """
        do something
        ....
        At the end,release the lock
        """
        lock.release()
def cs():
        lock=thread.allocate_lock()
        lock.acquire()
        thread.start_new_thread(Hello, ("Hello World",lock))
        while True:
            if not lock.locked():
                break
        print "lock release"
if __name__=='__main__':
    cs()

相关教程