David Blume commited on 2019-07-07 11:52:26
Showing 3 changed files, with 14 additions and 6 deletions.
... | ... |
@@ -68,6 +68,9 @@ I saved the best for last. The only thing the main thread does is bring the |
68 | 68 |
workers and the print manager to life. The workers each independently do their own loop: |
69 | 69 |
ping, compare, print, and wait. |
70 | 70 |
|
71 |
+Since the process thread doesn't have anything to do after spawning the workers, |
|
72 |
+it can be one of the workers. |
|
73 |
+ |
|
71 | 74 |
![Long Lived Looping Workers](http://dlma.com/images/python_pinger/ping_long_lived_looping_workers.png) |
72 | 75 |
|
73 | 76 |
See the source: **[long\_lived\_looping\_workers.py](http://git.dlma.com/python_pinger.git/blob/master/long_lived_looping_workers.py)** |
... | ... |
@@ -57,9 +57,12 @@ if __name__ == '__main__': |
57 | 57 |
|
58 | 58 |
log(f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}' |
59 | 59 |
f' PID={os.getpid()} repeat={parser_args.delay}s Starting') |
60 |
- for address in parser_args.addresses: |
|
60 |
+ |
|
61 |
+ # Create worker threads for all but one host address. (Saving one address for this thread.) |
|
62 |
+ for address in parser_args.addresses[:-1]: |
|
61 | 63 |
t = threading.Thread(target=pinger, args=(address, parser_args.delay), daemon=True) |
62 | 64 |
t.start() |
65 |
+ del t |
|
63 | 66 |
|
64 |
- # Stay alive forever. Join the last worker thread. |
|
65 |
- t.join() |
|
67 |
+ # Main thread becomes a worker pinger, too. |
|
68 |
+ pinger(parser_args.addresses[-1], parser_args.delay) |
... | ... |
@@ -68,10 +68,12 @@ if __name__ == '__main__': |
68 | 68 |
|
69 | 69 |
_print_queue.put([f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}' |
70 | 70 |
f' PID={os.getpid()} repeat={parser_args.delay}s Starting']) |
71 |
- for address in parser_args.addresses: |
|
71 |
+ |
|
72 |
+ # Create worker threads for all but one host address. (Saving one address for this thread.) |
|
73 |
+ for address in parser_args.addresses[:-1]: |
|
72 | 74 |
t = threading.Thread(target=pinger, args=(address, parser_args.delay), daemon=True) |
73 | 75 |
t.start() |
74 | 76 |
del t |
75 | 77 |
|
76 |
- # Stay alive forever. Join the infinitely looping print thread. |
|
77 |
- print_thread.join() |
|
78 |
+ # Main thread becomes a worker pinger, too. |
|
79 |
+ pinger(parser_args.addresses[-1], parser_args.delay) |
|
78 | 80 |