0

假设我有这样的代码:

def func1(a,b,c):
    try:
        p = pycurl.Curl()

        p.setopt(pycurl.PROXY, "127.0.0.1")
        p.setopt(pycurl.PROXYPORT, 9050)
        p.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5)

        p.perform()
        p.close()

    except pycurl.error as error:
        if error[0] == 28:   # timeout - change proxy
            print "Tor timeout, need to change"
            queue.put((a,b,c))
            new_tor()
            return

def new_tor():
    # send_signal_for_new_ident_is_here

我在 7 个线程中启动此代码。
当线程收到错误 28 时,它会更改标识。但是碰巧所有 7 个线程都发送信号来更改标识。

如何做到这一点:
如果线程收到错误 28,那么它调用 new_tor() 并且其他 6 个线程不等待结果,然后它们才继续工作。这个怎么同步?

4

1 回答 1

0

只需将错误“id”放入队列中,如果遇到,将值放回队列中,然后根据需要进行处理。

你不希望结束线程,这就是我所做的。
因此,您可以为每个线程设置一些唯一标识符,这样一旦线程遇到错误,它还会添加表示它之前遇到此错误的数据(它的标识符),以便如果所有线程都遇到此错误,则错误从队列中移除。

代码:

import threading
import Queue
y = 0
def f1():
    global y
    y += 1
    if y > 100:
        raise ValueError('trial')
def f2():
    return

class Test(threading.Thread):
    def __init__(self, func, name):
        threading.Thread.__init__(self)
        self.func = func
        self.name = name
    def run(self):
        while True:
            x = ''
            if not queue.empty():
                x = queue.get()
                if x == 'error':
                    queue.put(x)
                    print 'Stopping %s' % (self.name,)
                    return
            try:
                self.func()
            except Exception as e:
                queue.put('error')

queue = Queue.Queue()
thread1 = Test(f1, '1')
thread2 = Test(f2, '2')

thread1.start()
thread2.start()
于 2013-04-22T10:51:33.353 回答