from icmplib import ping
def main():
hosts = ['dns.google',
'family.cloudflare-dns.com',
'moodle.ncnu.edu.tw',
'sis.ncnu.edu.tw',
]
for host in hosts:
h = ping(host, privileged=False)
result = f"{host} ({h.address}) is\t"
if h.is_alive:
result += 'alive'
else:
result += 'unreachable'
print(result)
main()
real 0m20.171s
user 0m0.072s
sys 0m0.036s
from icmplib import ping
import threading
def probe(host):
h = ping(host, privileged=False)
result = f"{host} ({h.address}) is\t"
if h.is_alive:
result += 'alive'
else:
result += 'unreachable'
print(result)
def main():
hosts = ['dns.google',
'family.cloudflare-dns.com',
'moodle.ncnu.edu.tw',
'sis.ncnu.edu.tw',
]
for host in hosts:
t = threading.Thread(target=probe, args=(host,))
t.start()
main()
threading module, and use it to create threads to run
functions concurrently.
import threading
def worker():
"""thread worker function"""
print('Worker')
for i in range(5):
t = threading.Thread(target=worker)
t.start()
start() method.
args parameter to specify the arguments.
import threading
def worker(num):
"""thread worker function"""
print(f'Worker: {num}')
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
t.start()
import threading
import time
def worker():
print(threading.current_thread().name, 'Starting')
time.sleep(2)
print(threading.current_thread().name, 'Exiting')
def manager():
print(threading.current_thread().name, 'Starting')
time.sleep(3)
print(threading.current_thread().name, 'Exiting')
m = threading.Thread(name='Manager', target=manager)
w = threading.Thread(name='Worker', target=worker)
w1 = threading.Thread(target=worker) # use default name
w.start()
w1.start()
m.start()
print(threading.current_thread().name, 'Exiting')
print to debug.
import logging, threading, time
def worker():
logging.info('Starting')
time.sleep(2)
logging.debug('Exiting')
def manager():
logging.info('Starting')
time.sleep(3)
logging.debug('Exiting')
logging.basicConfig(
level=logging.DEBUG,
format='[%(levelname)s] (%(threadName)-10s) %(message)s',)
m = threading.Thread(name='Manager', target=manager)
w = threading.Thread(name='Worker', target=worker)
w1 = threading.Thread(target=worker) # use default name
w.start()
w1.start()
m.start()
logging.debug('Exiting')
levelname and threadName are automatically
shown.
import threading, time, logging
def daemon():
logging.info('Starting')
time.sleep(2)
logging.debug('Exiting')
def non_daemon():
logging.info('Starting')
logging.debug('Exiting')
logging.basicConfig(
level=logging.DEBUG,
format='[%(levelname)s] (%(threadName)-10s) %(message)s', )
d = threading.Thread(name='daemon', target=daemon, daemon=True)
n = threading.Thread(name='non-daemon', target=non_daemon)
d.start()
n.start()
import threading, logging, random, time
logging.basicConfig(
level=logging.INFO,
format='(%(threadName)-10s) %(message)s',
)
def worker():
i = random.randint(2, 10)
logging.info(f"Waiting {i} seconds")
time.sleep(i)
# b.wait()
logging.info("Exiting")
b = threading.Barrier(5)
for i in range(5):
t = threading.Thread(target=worker)
t.start()
import threading, logging, random, time
logging.basicConfig(
level=logging.INFO,
format='(%(threadName)-10s) %(message)s',
)
def worker():
i = random.randint(2, 10)
logging.info(f"Waiting {i} seconds")
time.sleep(i)
b.wait()
logging.info("First barrier passed")
time.sleep(i)
b.wait()
logging.info("Exiting")
b = threading.Barrier(5)
for i in range(5):
t = threading.Thread(target=worker)
t.start()
import threading, logging, time
logging.basicConfig(
level=logging.INFO,
format='(%(threadName)-10s) %(message)s',
)
def worker():
n = b.wait()
logging.info(f"Still {n} threads haven't passed the barrier.")
if n == 0:
time.sleep(0.1)
logging.info("I am the last one.")
b = threading.Barrier(5)
for i in range(5):
t = threading.Thread(target=worker)
t.start()
enumerate() returns a list of active Thread instances.
You don't need to maintain a list by yourself.
import threading ,time ,logging
def worker():
time.sleep(5)
logging.basicConfig(
level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
for i in range(3):
t = threading.Thread(target=worker)
t.start()
main_thread = threading.main_thread()
logging.debug(main_thread.name)
for t in threading.enumerate():
if t is not main_thread: # The list includes the current thread (main thread)
logging.debug(t.name)
import threading ,time ,logging, random
N = 3
status = [0]*N
def worker(num):
i = random.randint(2, 9)
logging.debug(f'Waiting {i} seconds.')
time.sleep(i)
status[num] = i
logging.basicConfig(
level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
for i in range(N):
t = threading.Thread(target=worker, args=(i,) )
t.start()
for i in range(N):
logging.debug(f'status[{i}] = {status[i]}')
status. However, the result shows that
it is not running as we expected.
import threading, time, logging, random
def worker():
n = random.randint(3, 8)
logging.info(f"I need {n} seconds.")
time.sleep(n)
logging.info("I am ready")
ready.set() # All threads waiting for it are awakened.
logging.basicConfig(
level=logging.INFO,
format='(%(threadName)-10s) %(message)s',
)
ready = threading.Event()
logging.info("Tell me when you are ready.")
t = threading.Thread(target=worker)
t.start()
ready.wait()
logging.info("OK")
import threading, time, logging, random
def worker(i):
if i % 2 == 1:
time.sleep(5)
ready.wait()
logging.info("I am ready")
logging.basicConfig(
level=logging.INFO,
format='(%(threadName)-10s) %(message)s',
)
ready = threading.Event()
for i in range(4):
t = threading.Thread(target=worker, name=f'Thread-{i}', args=(i,))
t.start()
ready.set()
import threading, time, logging, random
def worker(i):
if i % 2 == 1:
time.sleep(5)
ready.wait()
logging.info("I am ready")
logging.basicConfig(
level=logging.INFO,
format='(%(threadName)-10s) %(message)s',
)
ready = threading.Event()
for i in range(4):
t = threading.Thread(target=worker, args=(i,), daemon=True)
t.start()
ready.set()
ready.clear()
time.sleep(7)
# ready.set()
# time.sleep(1) # If you don't wait, the main thread will exit before daemon threads show responses.
import logging, threading, time
def server():
print("I'll sleep 30 seconds.")
INTERVAL=5
for i in range(6):
time.sleep(INTERVAL)
print("Have slept %d seconds" % ((i+1)*INTERVAL))
print("Ending server")
def client():
for i in range(3):
n = eval(input("? "))
if n == 0:
break
print("Ending client")
c = threading.Thread(target=client, daemon=True)
s = threading.Thread(target=server)
c.start()
s.start()
import logging, threading, time
def server():
print("I'll sleep 30 seconds.")
INTERVAL=5
for i in range(6):
if flagToExit.is_set(): # Initial value of the flag is False.
break
time.sleep(INTERVAL)
print("Have slept %d seconds" % ((i+1)*INTERVAL))
print("Ending server")
def client():
for i in range(3):
n = eval(input("? ")) # Input "0" to notify the server to terminate.
if n == 0:
break
flagToExit.set()
print("Ending client")
flagToExit = threading.Event()
c = threading.Thread(target=client, daemon=True)
s = threading.Thread(target=server)
c.start()
s.start()
import logging, threading, time
def server():
print("I'll sleep 30 seconds.")
INTERVAL=5
for i in range(6):
if flagToExit.wait(INTERVAL):
break
time.sleep(INTERVAL)
print("Have slept %d seconds" % ((i+1)*INTERVAL))
print("Ending server")
def client():
for i in range(3):
n = eval(input("? ")) # Input "0" to notify the server to terminate.
if n == 0:
break
flagToExit.set()
print("Ending client")
flagToExit = threading.Event()
c = threading.Thread(target=client, daemon=True)
s = threading.Thread(target=server)
c.start()
s.start()
from threading import Timer
def hello():
print("hello, world")
t = Timer(10.0, hello)
t.start() # after 10 seconds, "hello, world" will be printed
print("======")
print("Now trying to type some sentences.")
s = input()
print(s)
# ch07_thread_race1.py
import threading
import os.path
FN = "a.txt"
counter = 0 # Shared resource (counter)
def worker():
global counter
for _ in range(1000):
with open(FN, "r") as f:
s = f.readline()
if s == '':
counter = 0
else:
counter = int(s)
counter += 1
with open(FN, 'w') as f:
print(counter, file=f)
# Reset FN
with open(FN, 'w') as f:
print(0, file=f)
# Create and start two worker threads
thread1 = threading.Thread(target=worker)
thread2 = threading.Thread(target=worker)
thread1.start()
thread2.start()
# Wait for both threads to finish
thread1.join()
thread2.join()
print(f"Final counter value: {counter}")
# ch07_thread_race2.py
import threading
import os.path
FN = "a.txt"
counter = 0 # Shared resource (counter)
lock = threading.Lock()
def worker():
global counter
lock.acquire()
for _ in range(1000):
with open(FN, "r") as f:
s = f.readline()
if s == '':
counter = 0
else:
counter = int(s)
counter += 1
with open(FN, 'w') as f:
print(counter, file=f)
lock.release()
# Reset FN
with open(FN, 'w') as f:
print(0, file=f)
# Create and start two worker threads
thread1 = threading.Thread(target=worker)
thread2 = threading.Thread(target=worker)
thread1.start()
thread2.start()
# Wait for both threads to finish
thread1.join()
thread2.join()
print(f"Final counter value: {counter}")