Bonjour,
Après de bonnes heures de lectures et de tests, je bloque sur la methode pour stopper un code qui lui-même a lancé des threads.
Dans l'exemple ci-dessous, avec un timer pour donner une limitte d'execution, tout se passe bien, le code et ses threads sont correctements stoppés.
Sans le timer, je ne trouve pas le moyen de stopper tout ceci par un signal (ctrl+c ou kill -15).
Merci par avance pour votre aide.
Python 2.4 utilisé sur Debian.

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
 
class agent1(threading.Thread):
	def __init__(self, nom = ''):
		threading.Thread.__init__(self)
		self.nom = nom
		self._stopevent = threading.Event( )
		print datetime.datetime.now(),"Start",self.nom
	def run(self):
		while not self._stopevent.isSet():
			self._stopevent.wait(10 - (int(time.time()) % 10))
			print datetime.datetime.now(),"Run",self.nom
			## doing my job
	def stop(self):
		print datetime.datetime.now(),"Stop",self.nom
		self._stopevent.set( )
 
 
class agent2(threading.Thread):
	def __init__(self, nom = ''):
		threading.Thread.__init__(self)
		self.nom = nom
		self._stopevent = threading.Event( )
		print datetime.datetime.now(),"Start",self.nom
	def run(self):
		while not self._stopevent.isSet():
			self._stopevent.wait(20 - (int(time.time()) % 20))
			print datetime.datetime.now(),"Run",self.nom
			## doing my job
	def stop(self):
		print datetime.datetime.now(),"Stop",self.nom
		self._stopevent.set( )
 
 
def exit(signum,frame):
	a.stop()
	b.stop()
	print datetime.datetime.now(),"Exiting (%d) ..."%(signum)
	sys.exit(signum)
 
 
if __name__=="__main__":
	print datetime.datetime.now(),"Start"
 
	a = agent1('agent1')
	b = agent2('agent2')
 
	signal.signal(signal.SIGTERM, exit)
	signal.signal(signal.SIGINT, exit)
 
	a.start()
	b.start()
 
	#time.sleep(60.0)
	#a.stop()
	#b.stop()