|
| 1 | + |
| 2 | + |
| 3 | +Consider the python program given below in which we print thread name and corresponding process for each task: |
| 4 | + |
| 5 | +# Python program to illustrate the concept |
| 6 | +# of threading |
| 7 | +import threading |
| 8 | +import os |
| 9 | + |
| 10 | +def task1(): |
| 11 | + print("Task 1 assigned to thread: {}".format(threading.current_thread().name)) |
| 12 | + print("ID of process running task 1: {}".format(os.getpid())) |
| 13 | + |
| 14 | +def task2(): |
| 15 | + print("Task 2 assigned to thread: {}".format(threading.current_thread().name)) |
| 16 | + print("ID of process running task 2: {}".format(os.getpid())) |
| 17 | + |
| 18 | +if __name__ == "__main__": |
| 19 | + |
| 20 | + # print ID of current process |
| 21 | + print("ID of process running main program: {}".format(os.getpid())) |
| 22 | + |
| 23 | + # print name of main thread |
| 24 | + print("Main thread name: {}".format(threading.main_thread().name)) |
| 25 | + |
| 26 | + # creating threads |
| 27 | + t1 = threading.Thread(target=task1, name='t1') |
| 28 | + t2 = threading.Thread(target=task2, name='t2') |
| 29 | + |
| 30 | + # starting threads |
| 31 | + t1.start() |
| 32 | + t2.start() |
| 33 | + |
| 34 | + # wait until all threads finish |
| 35 | + t1.join() |
| 36 | + t2.join() |
| 37 | + |
| 38 | + |
0 commit comments