1import threading
2import time
3
4def func_1():
5 while True:
6 print(f"[{threading.current_thread().name}] Printing this message every 2 seconds")
7 time.sleep(2)
8
9# initiate the thread with daemon set to True
10daemon_thread = threading.Thread(target=func_1, name="daemon-thread", daemon=True)
11# or
12# daemon_thread.daemon = True
13# or
14# daemon_thread.setDaemon(True)
15daemon_thread.start()
16# sleep for 10 seconds and end the main thread
17time.sleep(4)
18# the main thread ends
1import threading
2import time
3
4def thread_function(name):
5 print(f"Thread {name}: starting")
6 time.sleep(2)
7 print(f"Thread {name}: finishing")
8
9my_thread = threading.Thread(target=thread_function, args=(1,))
10my_thread.start()
11time.sleep(1)
12my_second_thread = threading.Thread(target=thread_function, args=(2,))
13my_second_thread.start()
14my_second_thread.join() # Wait until thread finishes to exit
1import threading
2import time
3
4shared_resource = False # Set the resource to False initially
5lock = threading.Lock() # A lock for the shared resource
6
7def perform_computation():
8 # Thread A will call this function and manipulate the resource
9 print(f'Thread {threading.currentThread().name} - performing some computation....')
10 shared_resource = True
11 print(f'Thread {threading.currentThread().name} - set shared_resource to True!')
12 print(f'Thread {threading.currentThread().name} - Finished!')
13 time.sleep(1)
14
15def monitor_resource():
16 # Thread B will monitor the shared resource
17 while shared_resource == False:
18 time.sleep(1)
19 print(f'Daemon Thread {threading.currentThread().name} - Detected shared_resource = False')
20 time.sleep(1)
21 print(f'Daemon Thread {threading.currentThread().name} - Finished!')
22
23
24if __name__ == '__main__':
25 a = threading.Thread(target=perform_computation, name='A')
26 b = threading.Thread(target=monitor_resource, name='B', daemon=True) # Make thread B as a daemon thread
27
28 # Now start both threads
29 a.start()
30 b.start()
31
1
2import threading
3import time
4
5
6def print_work_a():
7 print('Starting of thread :', threading.currentThread().name)
8 time.sleep(2)
9 print('Finishing of thread :', threading.currentThread().name)
10
11
12def print_work_b():
13 print('Starting of thread :', threading.currentThread().name)
14 print('Finishing of thread :', threading.currentThread().name)
15
16a = threading.Thread(target=print_work_a, name='Thread-a')
17b = threading.Thread(target=print_work_b, name='Thread-b')
18
19a.start()
20b.start()
21
22