Threads modify "global" variable -- asking for trouble?

J Rice rice.jeffrey at
Fri Mar 17 04:58:36 CET 2006

I have been experimenting with some thread programming, but as I'm
doing this on my own I am worried I might be making a major mistake.

Here's a brief rundown of what I am working on.  Multiple threads, via
Queue, are used to perform RBL checks on an IP.  The threads are passed
a defined class (ConnectionScore) in their init.  This is used to
collect the results, including a method to add the result.  If I run
the program, everything goes fine and once all the threads complete the
main program has all the data from their RBL checks in the
ConnectionScore class.

It seems to work, even with an obscene (and silly) number of WORKERS
and RBLs to check.  But I was reading in the Python Cookbook this
evening and it raised the issue in my mind of what happens if multiple
threads try to add data to the class at the same time.

I've attached the code below.  The ConnectionClass.addRBL method just
takes the result and adds it to a dictionary object attached to the

from UCE_weight import ConnectionScore
from rbl import *
import Queue
import threading
import time, random

starttime = time.time()


class Worker(threading.Thread):

    def __init__(self,queue,score):
        self.__queue = queue
        self.score = score

    def run(self):
        while 1:
            RBL = self.__queue.get()
            # Are we at the end of the queue?
            if RBL is None: break
            self.result = checkRBL("",RBL,True,5)

queue = Queue.Queue(0)
score = ConnectionScore()

f = open("rbl.list",'r')
while 1:
    line = f.readline().strip()
    if not line: break

for i in range(WORKERS):
    Worker(queue,score).start() # start a worker

for i in MEGARBL:

for i in range(WORKERS):
    queue.put(None) # add end of queue marker

while 1:
    # wait for the queue???
    if queue.empty():

elapsed = time.time() - starttime
rate = len(MEGARBL)/elapsed
rate = str(round(rate,2))
elapsed = str(round(elapsed,2))

print "Checked",str(len(MEGARBL)),"zones in",elapsed,"seconds.
(",rate.strip(),"per second )"

More information about the Python-list mailing list