Threading and information passing -- how to

2024/9/20 8:15:13

To reframe from confusion i have edited the question:

one.py

import threading
count = 5
dev = threading.Thread(name='dev', target=dev,args=(workQueue,count,))
dev.setDaemon(True)
dev.start()
workQueue = Queue.Queue(10)
queueLock.acquire()
workQueue.put(word)
queueLock.release()
count = 3
time.sleep(2)
count = 5

but my confusion here is I am able to put and get values from queue between threads but in case of count it does not reflect.

Why is that?
What is point am actually missing here?

class dev ( threading.Thread ):def test(self):while 1:print countprint self.EPP_ObjqueueLock.acquire()if not self.workQueue.empty():data = self.workQueue.get()print dataqueueLock.release()else:queueLock.release()def __init__(self, workQueue, EPP_Obj):threading.Thread.__init__(self)self.workQueue = workQueueself.EPP_Obj = EPP_Obj
Answer

Let's start with an example:

The Thread subclass:

import threadingclass Dev(threading.Thread):def __init__(self, workQueue, queueLock, count):super(Dev, self).__init__()   # super() will call Thread.__init__ for youself.workQueue = workQueueself.queueLock= queueLockself.count = countdef run(self):  # put inside run your loopdata = ''while 1:with self.queueLock:if not self.workQueue.empty():data = self.workQueue.get()print dataprint self.countif data == 'quit':break

The with statement is a smart way to acquire and release a lock, take a look at the doc.

Now the running code:

import Queue
import timework_q = Queue.Queue()     # first create your "work object"
q_lock = threading.Lock()
count = 1dev = Dev(work_q, q_lock, count)  # after instantiate like this your Thread
dev.setDaemon(True)
dev.start()time.sleep(1)
with q_lock:work_q.put('word')
# word
# 1time.sleep(1)
count = 10
with q_lock:work_q.put('dog')
# dog
# 1count = 'foo'
with q_lock:work_q.put('quit')
# quit
# 1dev.join()   # This will prevent the main to exit# while the dev thread is still running

With the code above we have a clear example on how self.count stays unchanged no matter what we do to count.
The reason of this behaviour is that calling:

dev = Dev(work_q, q_lock, count)

or

dev = Dev(work_q, q_lock, 1)

is the same thing.

Arnold Moon Showed you a way to change self.count. Adjusting that to our example:

class Dev(threading.Thread):def __init__(self, workQueue, queueLock, count):super(Dev, self).__init__()self.workQueue = workQueueself.queueLock= queueLockself.count = countdef set_count(self, value):self.count = valuedef run(self):data = ''while 1:with self.queueLock:if not self.workQueue.empty():data = self.workQueue.get()print dataprint self.countif data == 'quit':break

Calling set_count in our running code will change the value of self.count:

time.sleep(1)
with q_lock:work_q.put('word')
# word
# 1time.sleep(1)
count = dev.count + 9
dev.set_count(count)
with q_lock:work_q.put('dog')
# dog
# 10count = 'foo'
with q_lock:work_q.put('quit')
# quit
# 10
dev.join()

I hope this will help you clarify some doubts.

https://en.xdnf.cn/q/72374.html

Related Q&A

How to rename a node with Python LXML?

How do I rename a node using LXML? Specifically, how to rename a parent node i.e. a <body> tag while preserving all the underlying structure? I am parsing using the lxml.html module but suppos…

In python, selenium, how do I set the error messages for a wait?

I have the following code:WebDriverWait(self.driver, 20).until(expected_conditions.element_to_be_clickable(click))Now this sometimes fails and I know why it fails. But the error gives me TimeoutExcept…

Python: the mechanism behind list comprehension

When using list comprehension or the in keyword in a for loop context, i.e:for o in X:do_something_with(o)orl=[o for o in X]How does the mechanism behind in works? Which functions\methods within X do…

PRAW: Comment Submitters Username

Im developing a reddit bot that needs to know which user submitted a comment. According to the PRAW API wrapper docs, theres no specific way to get the username of a Comment objects author. Ideally I c…

Paramiko, exec_command get the output stream continuously [duplicate]

This question already has answers here:Get output from a Paramiko SSH exec_command continuously(6 answers)Closed 2 years ago.I dry on a Python script. I create a python script for a given IP will conne…

pdfminer3k has no method named create_pages in PDFPage

Since I want to move from python 2 to 3, I tried to work with pdfmine.3kr in python 3.4. It seems like they have edited everything. Their change logs do not reflect the changes they have done but I had…

curve fitting zipf distribution matplotlib python

I tried to fit the following plot(red dot) with the Zipf distribution PDF in Python, F~x^(-a). I simply chose a=0.56 and plotted y = x^(-0.56), and I got the curve shown below. The curve is obviously …

Running python/ruby script on iPhone?

From the recent news from the Apple, I learned that one has to use C/C++/Objective-C for iPhone App. Accordingly, its not possible to use MacPython or similar to make iPhone App. But as the python/ruby…

Unexpected behavior of universal newline mode with StringIO and csv modules

Consider the following (Python 3.2 under Windows):>>> import io >>> import csv >>> output = io.StringIO() # default parameter newline=None >>> csvdata = [1, …

logger chain in python

Im writing python package/module and would like the logging messages mention what module/class/function they come from. I.e. if I run this code:import mymodule.utils.worker as workerw = worker.Worker()…