Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #10461

Re: Seeking an example on using Queue to update variable while threading

Path csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!feeder.news-service.com!newsfeed.xs4all.nl!newsfeed5.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail
Return-Path <kushal.kumaran@gmail.com>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.000
X-Spam-Evidence '*H*': 1.00; '*S*': 0.00; 'subject:using': 0.04; 'main()': 0.05; 'sys': 0.05; 'function,': 0.07; 'subject:while': 0.07; 'python': 0.08; '__name__': 0.09; 'collections': 0.09; 'danny': 0.09; 'dict': 0.09; 'generators': 0.09; 'none:': 0.09; 'output': 0.11; 'am,': 0.13; 'wrote:': 0.15; "'__main__':": 0.16; 'dummy': 0.16; 'intervals.': 0.16; 'main():': 0.16; 'name):': 0.16; 'subject:example': 0.16; 'subject:variable': 0.16; 'thread.': 0.16; 'threading': 0.16; "\xc2\xa0i'm": 0.16; 'cc:addr :python-list': 0.16; 'this:': 0.16; 'def': 0.16; 'received:74.125.82.44': 0.19; 'received:mail-ww0-f44.google.com': 0.19; 'cc:2**0': 0.21; 'cc:no real name:2**0': 0.22; 'header:In- Reply-To:1': 0.22; 'trying': 0.23; 'works.': 0.23; 'structure': 0.23; 'runs': 0.23; 'receives': 0.25; 'function': 0.26; 'sender:addr:gmail.com': 0.26; "i'm": 0.27; 'random': 0.28; 'thu,': 0.28; 'message-id:@mail.gmail.com': 0.28; 'import': 0.29; 'cc:addr:python.org': 0.30; 'example': 0.30; 'hash': 0.30; 'queue': 0.30; 'skip:% 10': 0.30; 'subject:update': 0.30; 'threads': 0.30; 'threads.': 0.30; 'values': 0.31; 'does': 0.32; 'anyone': 0.33; 'actually': 0.33; 'follows:': 0.34; 'example,': 0.35; 'function.': 0.35; 'sense,': 0.35; 'data,': 0.35; 'data.': 0.36; 'familiar': 0.36; 'thread': 0.37; 'but': 0.37; 'using': 0.37; 'received:google.com': 0.38; 'subject:: ': 0.38; 'run': 0.39; 'finished': 0.39; 'received:74.125.82': 0.39; 'might': 0.39; 'received:74.125': 0.40; 'skip:r 20': 0.40; 'your': 0.60; 'waiting': 0.62; 'share': 0.68
DKIM-Signature v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=gamma; h=mime-version:sender:in-reply-to:references:from:date :x-google-sender-auth:message-id:subject:to:cc:content-type :content-transfer-encoding; bh=//Je821rWzVdbrxu2G+pLQ2htp2wRmFvF0XIMzgTQxU=; b=pljzXlgVKwW5YFuOjFEMyt5tSZKuEqxsHR3ghTIxciv0p5Crs0uR6L46XgtslPYnBc RpNjARb7sp8Vcvn7aUwLAczPB09NhbAq3oR6cqGJYa1tiCfIY5FZ1YGdGLKHWMWVuP2m sh0p9XmXft+xxy6lD1KkIIMf/Hr88v1ElScbw=
MIME-Version 1.0
Sender kushal.kumaran@gmail.com
In-Reply-To <D59C59453D0EDC43832490B6DADFAECF042686B8@XMB-RCD-214.cisco.com>
References <20110727080557.194B.1CBB3534@gmail.com> <j0nut4$iln$1@dough.gmane.org> <j0ocpl$l25$1@dough.gmane.org> <D59C59453D0EDC43832490B6DADFAECF042686B8@XMB-RCD-214.cisco.com>
From Kushal Kumaran <kushal.kumaran+python@gmail.com>
Date Thu, 28 Jul 2011 21:27:32 +0530
X-Google-Sender-Auth yv8PmK38BmG2ij50hMQoXTqYt78
Subject Re: Seeking an example on using Queue to update variable while threading
To "Danny Wong (dannwong)" <dannwong@cisco.com>
Content-Type text/plain; charset=UTF-8
Content-Transfer-Encoding quoted-printable
Cc python-list@python.org
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.12
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <http://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <http://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Newsgroups comp.lang.python
Message-ID <mailman.1576.1311868673.1164.python-list@python.org> (permalink)
Lines 109
NNTP-Posting-Host 2001:888:2000:d::a6
X-Trace 1311868673 news.xs4all.nl 23835 [2001:888:2000:d::a6]:39759
X-Complaints-To abuse@xs4all.nl
Xref x330-a1.tempe.blueboxinc.net comp.lang.python:10461

Show key headers only | View raw


On Thu, Jul 28, 2011 at 11:13 AM, Danny Wong (dannwong)
<dannwong@cisco.com> wrote:
> Hi Python experts,
>        I'm trying to use a dict structure to store and update information from X number of threads. How do I share this dict structure between threads? I heard of using a queue, but I'm not familiar with how it works. Does anyone have an example of using a queue to store variables/dicts between threads?
>

With a queue, you would not actually share data.  One of your threads
will "own" the data, and the other threads will send messages to the
owner to update the data.  These messages will be sent on a queue,
which the owner thread is waiting on.  A dummy example follows:

import threading
import time
import random
import queue
import collections
import logging
import sys

def generator_func(q, name):
    for i in range(1000):
        time.sleep(random.randint(1, 10))
        value = random.randint(1, 100)
        logging.info('generated {}'.format(value))
        q.put(value)
    logging.info('finished')
    q.put(None)

def counter_func(q, num_generators):
    counts = collections.defaultdict(int)
    finished = 0
    while True:
        item = q.get()
        if item is None:
            finished += 1
            if finished == num_generators:
                return
        logging.info('received {}'.format(item))
        counts[item] += 1

def main():
    num_generators = 50

    logging.basicConfig(level=logging.DEBUG, stream=sys.stdout,
                        format="%(asctime)s %(threadName)s %(message)s")

    q = queue.Queue()
    counter = threading.Thread(name='counter', target=counter_func,
                               args=(q, num_generators))
    counter.start()

    generators = []
    for i in range(num_generators):
        generators.append(threading.Thread(name='generator-{:03}'.format(i),
                                           target=generator_func, args=(q, i)))
        generators[-1].start()

    counter.join()
    for g in generators:
        g.join()

if __name__ == '__main__':
    main()

The "counter" thread runs the counter_func function.  This function
waits on a queue and updates a hash when it receives an item on the
queue.  The "generator" threads run the generator_func function, which
puts random values into the queue at random intervals.  So, in a
sense, the "generator" threads update the hash by sending messages to
the "counter" thread.

If you run this example, you might see output like this:

2011-07-28 21:23:40,445 generator-001 generated 55
2011-07-28 21:23:40,448 generator-026 generated 38
2011-07-28 21:23:40,448 generator-015 generated 62
2011-07-28 21:23:40,448 generator-009 generated 90
2011-07-28 21:23:40,459 counter received 55
2011-07-28 21:23:40,455 generator-039 generated 72
2011-07-28 21:23:40,460 counter received 38
2011-07-28 21:23:40,460 counter received 90
2011-07-28 21:23:40,460 counter received 62
2011-07-28 21:23:40,461 counter received 72
2011-07-28 21:23:41,447 generator-012 generated 12
2011-07-28 21:23:41,448 generator-029 generated 49
2011-07-28 21:23:41,448 generator-023 generated 11
2011-07-28 21:23:41,449 counter received 12
2011-07-28 21:23:41,449 generator-041 generated 91
2011-07-28 21:23:41,449 generator-049 generated 20
2011-07-28 21:23:41,449 generator-042 generated 73
2011-07-28 21:23:41,450 counter received 49
2011-07-28 21:23:41,451 counter received 11
2011-07-28 21:23:41,451 counter received 91
2011-07-28 21:23:41,452 counter received 20
2011-07-28 21:23:41,452 counter received 73
2011-07-28 21:23:41,461 generator-039 generated 85
2011-07-28 21:23:41,462 counter received 85
...


-- 
regards,
kushal

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Seeking an example on using Queue to update variable while threading Kushal Kumaran <kushal.kumaran+python@gmail.com> - 2011-07-28 21:27 +0530

csiph-web