473,781 Members | 2,732 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

getting a thread out of sleep

Right now I have a thread that sleeps for sometime and check if an
event has happened and go back to sleep. Now instead I want the thread
to sleep until the event has occured process the event and go back to
sleep. How to do this?
thanks
mark
class eventhndler(thr eading.Thread):
def __init__(self):
threading.Threa d.__init__(self )

def run(self):
while True:
time.sleep(SLEE PTIME)
''''do event stuff'''
Feb 21 '07
11 1957
On Feb 22, 12:08 pm, mark <rkmr...@gmail. comwrote:
On 21 Feb 2007 16:10:51 -0800, placid <Bul...@gmail.c omwrote:
On Feb 22, 10:20 am, mark <rkmr...@gmail. comwrote:
On 21 Feb 2007 14:47:50 -0800, placid <Bul...@gmail.c omwrote:
On Feb 22, 3:23 am, mark <rkmr...@gmail. comwrote:
On 20 Feb 2007 21:26:18 -0800, placid <Bul...@gmail.c omwrote:
On Feb 21, 4:21 pm, "placid" <Bul...@gmail.c omwrote:
On Feb 21, 4:12 pm, mark <rkmr...@gmail. comwrote:
On 20 Feb 2007 20:47:57 -0800, placid <Bul...@gmail.c omwrote:
On Feb 21, 3:08 pm, mark <rkmr...@gmail. comwrote:
Right now I have a thread that sleeps for sometime and check if an
event has happened and go back to sleep. Now instead I want the thread
to sleep until the event has occured process the event and go back to sleep
class eventhndler(thr eading.Thread):
def __init__(self):
threading.Threa d.__init__(self )
def run(self):
while True:
time.sleep(SLEE PTIME)
''''do event stuff'''
The way i would do this is by using an threading.Event (
>http://docs.python.org/lib/event-objects.html)
<code>
class eventhandler(th reading.Thread) :
def __init__(self):
threading.Threa d.__init__(self )
self.event = threading.Event ()
def run:
while True:
# block until some event happens
self.event.wait ()
""" do stuff here """
self.event.clea r()
</code>
the way to use this is to get the main/separate thread to set() the
event object.
Can you give an example of how to get the main threead to set teh event object?
this is exactly what i wanted to do!
thanks a lot!
mark>
oops I've miss-typed the thread variable name the following should
work
<code>
if __name__ == "__main__":
evtHandlerThrea d = eventhandler()
evtHandlerThrea d.start()
# do something here #
evtHandlerThrea d.event.set()
# do more stuff here #
evtHandlerThrea d.event.set()
</code>
Can I have the same thread process two or more events? Can you tell
how to do this? The code you gave is waiting on one event right. How
can I do it for more events?
thanks a lot!
mark
I don't think a thread can block on more than one event at a time. But
you can make it block on more then one event one at a time.
<code>
class eventhandler(th reading.Thread) :
def __init__(self):
threading.Threa d.__init__(self )
self.events = [threading.Event (), threading.Event ()]
self.currentEve nt = None
def run:
while True:
for event in self.events:
self.currentEve nt = event
# block until some event happens
self.currentEve nt.wait()
""" do stuff here """
self.currentEve nt.clear()
if __name__ == "__main__":
evtHandlerThrea d = eventhandler()
evtHandlerThrea d.start()
# do something here #
evtHandlerThrea d.currentEvent. set()
# do more stuff here #
evtHandlerThrea d.currentEvent. set()
</code>
what the thread does is sequentially waits for two events to happen
and then execute the same code. You could change this code to perform
different functions for different event objects.
Once the thread starts it is going to wait on the event that is the
first element of the list right? This would mean :
This is correct.
evtHandlerThrea d.currentEvent. set(): that I have only one event right?
this means that the current event occurred.
Can you explain how I can have different event objects. I dont see how
I can do different functinos for same event.
Thanks a lot!
mark
To run different functions for the same event is easy, just write a
wrapper class around threading.event () and include some method that
you will run and assign this to different functions for each
EventWrapper.
<code>
class EventWrapper():
def __init__(self,w ork ):
self.event = threading.Event ()
self.eventWork = work
def wait(self):
self.event.wait ()
def clear(self)
self.event.clea r()
def eventWork(self) :
print "no work"
class eventhandler(th reading.Thread) :
def __init__(self, events = None):
threading.Threa d.__init__(self )
self.events = events
self.currentEve nt = None
def run:
while True:
if self.events:
for event in self.events:
self.currentEve nt = event
# block until the current event happens
self.currentEve nt.wait()
self.currentEve nt.eventWork()
self.currentEve nt.clear()
def eventOneWork():
# do some event 1 specific work here
def eventTwoWork():
# do some event 2 specific work here
if __name__ == "__main__":
events = [EventWrapper(ev entOneWork),Eve ntWrapper(event TwoWork)]
evtHandlerThrea d = eventhandler(ev ents)
evtHandlerThrea d.start()
# do something here #
evtHandlerThrea d.currentEvent. set()
# do more stuff here #
evtHandlerThrea d.currentEvent. set()
</code>
So you have a EventWrapper class that now contains the Event object
and a workEvent() method which is assigned to a function you create.

THanks a lot! Does this have to have event1 and event2 occur in
sequence? Will this still work even if only event2 occurs and event1
never occurs?
thanks
mark
well if event1 never occurs then it will block/wait until forever and
even if event2 has occurred you never know about it until event1
occurs. You can introduce a timeout to the wait() call on the event
object which says, "block X seconds or until event happens (someone
calls the set method)" so even if event1 doesnt occur you will execute
event1.eventWor k() because the timeout occurred. The way to fix this
is before you call the eventWork() method check if the event has
occurred via the isSet() method of Event objects.

http://docs.python.org/lib/event-objects.html

Cheers

Feb 22 '07 #11
placid wrote:
On Feb 22, 12:08 pm, mark <rkmr...@gmail. comwrote:
>On 21 Feb 2007 16:10:51 -0800, placid <Bul...@gmail.c omwrote:
>>On Feb 22, 10:20 am, mark <rkmr...@gmail. comwrote:
On 21 Feb 2007 14:47:50 -0800, placid <Bul...@gmail.c omwrote:
On Feb 22, 3:23 am, mark <rkmr...@gmail. comwrote:
>On 20 Feb 2007 21:26:18 -0800, placid <Bul...@gmail.c omwrote:
>>On Feb 21, 4:21 pm, "placid" <Bul...@gmail.c omwrote:
>>>On Feb 21, 4:12 pm, mark <rkmr...@gmail. comwrote:
>>>>On 20 Feb 2007 20:47:57 -0800, placid <Bul...@gmail.c omwrote:
>>>>>On Feb 21, 3:08 pm, mark <rkmr...@gmail. comwrote:
>>>>>>Rig ht now I have a thread that sleeps for sometime and check if an
[...]
Perhaps in future we can avoid quoting the whole preceding thread except
when strictly necessary?

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note: http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

Feb 22 '07 #12

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

Similar topics

8
2305
by: andrewpalumbo | last post by:
I'm trying to write some code which will split up a vector into two halves and run a method on the objects in the vector using two seperate threads. I was hoping to see a near linear speedup on an SMP machine, but I'm finding that the code below takes almost exactly the same amount of time as when I iterate through the vector, and don't use any threads at all (using only one processor). I'm running this on a Dual Athlon machine under...
8
2785
by: Cider123 | last post by:
I ran into a situation where my Window Service had to process 100,000+ files, when I first noticed I needed to tweak various routines. Everything runs fine, but here's what I ran into: In the routine that loops through the file buffer: for (int i=0;i < _Buffer.length; i++) { // Code here
18
6866
by: Zytan | last post by:
I have multiple threads writing to WebBrowser (using a function that checks InvokedRequired, and if so, invokes itself on the WebBrowser thread) and they are getting deadlocked. They only deadlock when I use lock { } around the call to WebBrowser.Write to ensure thread safety! Does any one have experience with such a thing? Zytan
2
3370
by: Steve | last post by:
Hi All, I've been trying to come up with a good way to run a certain process at a timed interval (say every 5 mins) using the SLEEP command and a semaphore flag. The basic thread loop was always sitting in the sleep command and not able to be interrupted. When the time came to set the semaphore flag to false (stopping the thread), my program would have to wait up to the entire sleep time to break out of the loop. I have finally found...
0
9639
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
10308
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10143
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...
0
9939
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8964
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...
0
6729
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4040
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3633
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2870
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.