473,769 Members | 3,755 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

I don't understand what is happening in this threading code

In this code, I tried to kill my thread object by setting a variable on it
to False.

Inside the run method of my thread object, it checks a different
variable.

I've already rewritten this code to use semaphores, but I'm just curious
what is going on.

Here's the code:

import logging, threading, time
logging.basicCo nfig(level=logg ing.DEBUG,
format="%(threa dName)s: %(message)s")

class Waiter(threadin g.Thread):
def __init__(self, hot_food):
super(Waiter, self).__init__( )
self.should_kee p_running = True
self.hot_food = hot_food

def run(self):
while self.should_kee p_running:
logging.debug(" Inside run, the id of should_keep_run ning is %s."
% id(self.should_ keep_running))
self.hot_food.a cquire()

def cook_food(hot_f ood):
i = 5
while i >= 0:
logging.debug(" I am cooking food...")
time.sleep(1)
hot_food.releas e()
logging.debug(" Andiamo!")
i -= 1

def main():

hot_food = threading.Semap hore(value=0)

chef = threading.Threa d(name="chef", target=cook_foo d, args=(hot_food, ))
chef.start()

w = Waiter(hot_food )
logging.debug(" Initially, the id of w.should_keep_r unning is %s."
% id(w.should_kee p_running))
w.start()
logging.debug(" After start, the id of w.should_keep_r unning is %s."
% id(w.should_kee p_running))

# Wait for the chef to finish work.
chef.join()

# Now try to kill off the waiter by setting a variable inside the waiter.
w.should_keep_r unning = False
logging.debug(" Now, the id of w.should_keep_r unning is %s."
% id(w.should_kee p_running))

if __name__ == "__main__":
main()

And here's what I get when I execute it. I have to suspend the process
with CTRL=Z and then kill -9 it.

$ python foo.py
MainThread: Initially, the id of w.should_keep_r unning is 135527852.
MainThread: After start, the id of w.should_keep_r unning is 135527852.
chef: I am cooking food...
Thread-1: Inside run, the id of should_keep_run ning is 135527852.
chef: Andiamo!
chef: I am cooking food...
Thread-1: Inside run, the id of should_keep_run ning is 135527852.
chef: Andiamo!
chef: I am cooking food...
Thread-1: Inside run, the id of should_keep_run ning is 135527852.
chef: Andiamo!
chef: I am cooking food...
Thread-1: Inside run, the id of should_keep_run ning is 135527852.
chef: Andiamo!
chef: I am cooking food...
Thread-1: Inside run, the id of should_keep_run ning is 135527852.
chef: Andiamo!
chef: I am cooking food...
Thread-1: Inside run, the id of should_keep_run ning is 135527852.
chef: Andiamo!
Thread-1: Inside run, the id of should_keep_run ning is 135527852.
MainThread: Now, the id of w.should_keep_r unning is 135527840.

[1]+ Stopped python foo.py

$ kill -9 %1

[1]+ Stopped python foo.py

The memory address of should_keep_run ning seems to change when I set it
from True to False, and inside the run method, I keep checking the old
location.

I am totally baffled what this means.

Like I said earlier, I already rewrote this code to use semaphores, but
I just want to know what is going on here.

Any explanation is welcome.

TIA

Matt
Jan 19 '08 #1
2 1500
On Jan 18, 7:43 pm, Matthew Wilson <m...@tplus1.co mwrote:
In this code, I tried to kill my thread object by setting a variable on it
to False.

Inside the run method of my thread object, it checks a different
variable.

I've already rewritten this code to use semaphores, but I'm just curious
what is going on.

Here's the code:

import logging, threading, time
logging.basicCo nfig(level=logg ing.DEBUG,
format="%(threa dName)s: %(message)s")

class Waiter(threadin g.Thread):
def __init__(self, hot_food):
super(Waiter, self).__init__( )
self.should_kee p_running = True
self.hot_food = hot_food

def run(self):
while self.should_kee p_running:
logging.debug(" Inside run, the id of should_keep_run ning is %s."
% id(self.should_ keep_running))
self.hot_food.a cquire()

def cook_food(hot_f ood):
i = 5
while i >= 0:
logging.debug(" I am cooking food...")
time.sleep(1)
hot_food.releas e()
logging.debug(" Andiamo!")
i -= 1

def main():

hot_food = threading.Semap hore(value=0)

chef = threading.Threa d(name="chef", target=cook_foo d, args=(hot_food, ))
chef.start()

w = Waiter(hot_food )
logging.debug(" Initially, the id of w.should_keep_r unning is %s."
% id(w.should_kee p_running))
w.start()
logging.debug(" After start, the id of w.should_keep_r unning is %s."
% id(w.should_kee p_running))

# Wait for the chef to finish work.
chef.join()

# Now try to kill off the waiter by setting a variable inside the waiter.
w.should_keep_r unning = False
logging.debug(" Now, the id of w.should_keep_r unning is %s."
% id(w.should_kee p_running))

if __name__ == "__main__":
main()

It looks like your program's hanging while the waiter is waits to
acquire another plate of hot food.

Quick and dirty solution is to have waiter timeout at intervals while
waiting for the chef and check the clock to see if his shift has
ended. Better solution is to rewrite the logic, which you did.
Carl Banks
Jan 19 '08 #2
Matthew Wilson <ma**@tplus1.co mwrote:
>In this code, I tried to kill my thread object by setting a variable on it
to False.

Inside the run method of my thread object, it checks a different
variable.

I've already rewritten this code to use semaphores, but I'm just curious
what is going on.
...
The memory address of should_keep_run ning seems to change when I set it
from True to False, and inside the run method, I keep checking the old
location.
You misunderstand what "id(a)" does. "id" doesn't tell you anything about
the name "a" or the address of "a". What it tells you is the unique
identifier of the object that "a" is bound to. Any time you change "a",
"id(a)" will also change.

Note, for example:

C:\tmp>python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright" , "credits" or "license" for more information.
>>id(True)
504958236
>>a = True
id(a)
504958236
>>id(False)
504958224
>>a = False
b = False
id(a)
504958224
>>id(b)
504958224
>>>
504958236 is the id of "True", not of "a".
--
Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Jan 22 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1456
by: L'astemio | last post by:
hi all i must send a mail from a php form. ok. i have pear installed. ok. this is my code: <? include("Mail.php"); $recipients = "info@domain.com"; $headers = "info@domain.com";
2
2986
by: Egor Bolonev | last post by:
hi all my program terminates with error i dont know why it tells 'TypeError: run() takes exactly 1 argument (10 given)' =program==================== import os, os.path, threading, sys def get_all_files(path): """return all files of folder path, scan with subfolders
2
1697
by: pokémon | last post by:
OK, if you run this code below (Console app) you will find that threads will not always behave in a synchronized fashion, even with a lock statement, --unless you put a Sleep somewhere in the method passed to ThreadStart. Try it, and please prove me wrong. ******** using System; using System.Threading;
0
1111
by: CMEDIA_SOUND | last post by:
I have a peculiar problem, I have a tabpage with a label control on it. When i set a background image to the tabpage and drag the label around it has paint issues in that it is slow, granted the image i am using is 5mb!!! HOWEVER... I have inherited the tabpage created an Image reference in it, and overrriden the onPaint method to draw the image now if i press a button that sets the background image of the control
19
3882
by: LP | last post by:
I am using (trying to) CR version XI, cascading parameters feature works it asks user to enter params. But if page is resubmitted. It prompts for params again. I did set ReuseParameterValuesOnRefresh="True" in a viewer, but it still doesn't work. Did anyone run into this problem. What's the solution? Please help. Thank you
3
2014
by: smorrey | last post by:
Howdy folks, I recently purchased a book on C++ MUD creation and it features alot of nifty tidbits. The book is MUD GAME PROGRAMMING by Ron Penton Publisher: Premier Press Anyways of particular interest and what drew me to the book was the crossplatform threading library. But the problem is it appears to be broken at a single line of code,
31
1923
by: Jo | last post by:
class A { public: char text_a; A() { *text_a=0; } ~A() {} }; //-----------------------------------------------------------------------------
7
1266
by: lordango | last post by:
class Program { public void test(int i) { if (i > 0) { test(--i); } Console.WriteLine(i); }
5
2601
by: Thierry | last post by:
Hello fellow pythonists, I'm a relatively new python developer, and I try to adjust my understanding about "how things works" to python, but I have hit a block, that I cannot understand. I needed to output unicode datas back from a web service, and could not get back unicode/multibyte text before applying an hack that I don't understand (thank you google) I have realized an wxPython simple application, that takes the input
0
9583
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10039
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9990
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8869
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7406
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5297
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5445
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3560
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2814
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.