473,785 Members | 2,275 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

thread and alarm

How to send alarm to a thread?
I can set alarm in main thread, but how then send exception to another thread to wake it if it executes too long?
Dec 16 '05 #1
1 1982
Op 2005-12-16, Sergey schreef <s3**@mail.ru >:
How to send alarm to a thread?
I can set alarm in main thread, but how then send exception to another thread to wake it if it executes too long?


The short answer is you can't and you should preferably look for an
other solution. If for example your other thread is simple loop
like:

while condition:
...

You could change this to:

while not timeout and condition:

timeout is then a variable that could be set by a differnt thread.
If your code doesn't lend itself for this kind of solution you could
consider the following module I once wrote. However some caveats:

1) You need ctypes.

2) It can only interrupt a thread while it is excuting python
code. No interruptions while in C-extention code.

3) It is not extensivly tested. It was just a proof of concept
thing.

----

import os
import ctypes
from time import sleep
from random import randint

class TimeOut(Excepti on):
pass

class Alarm(Exception ):
pass

import threading

class Xthread(threadi ng.Thread):
def start(self):
self.__original _run = self.run
self.run = self.__run
threading.Threa d.start(self)

def __run(self):
self._thrd_id = threading._get_ ident()
try:
self.__original _run()
finally:
self.run = self.__original _run

def raize(self, excpt):

Nr = ctypes.pythonap i.PyThreadState _SetAsyncExc(se lf._thrd_id, ctypes.py_objec t(excpt))
#print self.id , "Exception Thrown" , Nr
while Nr > 1:
#print self.id , "Exception Canceled" , Nr
ctypes.pythonap i.PyThreadState _SetAsyncExc(se lf._thrd_id, None)
sleep(0.1)
Nr = ctypes.pythonap i.PyThreadState _SetAsyncExc(se lf._thrd_id, ctypes.py_objec t(excpt))
#if Nr == 0:
# print self.id , "Exception Canceled" , Nr
# ctypes.pythonap i.PyThreadState _SetAsyncExc(se lf._thrd_id, None)

def alarm(self, tm):

alrm = threading.Timer (tm, self.raize, (TimeOut,))
alrm.start()
return alrm

if __name__ == "__main__":

class Continue(Xthrea d):

def run(self):

self.id = os.getpid()
print self.id, self._thrd_id, "Begin"
i = 0
try:
for _ in xrange(randint( 0,20)):
for e in xrange(4 * 100000):
i = i + e
print self.id, "Finished"
except Alarm:
print self.id, "Interupted "

lst = [Continue() for _ in xrange(10)]

for T in lst:
T.start()

try:
sleep(10)
finally:
for T in lst:
T.raize(Alarm)
Dec 16 '05 #2

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

Similar topics

7
11082
by: Adrian Casey | last post by:
I have a multi-threaded python application which uses pexpect to connect to multiple systems concurrently. Each thread within my application is a connection to a remote system. The problem is when one of the child threads runs a command which generates an unlimited amount of output. The classic example of this is the "yes" command. If you execute "pexpect.run('yes')", your cpu will sit at 100% forever. Here is a simple multi-threaded...
4
42630
by: Gary Wessle | last post by:
Hi given the Boost thread example here http://www-eleves-isia.cma.fr/documentation/BoostDoc/boost_1_29_0/libs/thread/example/thread.cpp the code below attempts to run the example thread while giving the user a prompt for data input. I am failing to get the prompt while the thread is running, what am I doing wrong?
4
5164
by: liu yang | last post by:
I want to build a timer for each thread, and the timer must be thread- safe. How to do that? My environment is Linux and Pthread. Thanks.
2
1601
by: machado | last post by:
Greetings. I have a program in VB2008 and I need to execute a thread from differents Subs. Each time I start the thread I want to cancel the previous. Here an example: Private Sub TextBox_Changed(ByVal sender As System.Object, ByVal e As System.EventArgs) Dim ThreadResults As New Thread(AddressOf ShowResults) ThreadResults.Start() End Sub
0
9489
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10162
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
10101
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
9959
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
6744
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();...
0
5396
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...
1
4063
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
3665
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2893
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.