4. Handling parameters
In the theoretical section, we have considered processes and threads. Threads are light-weight processes running within a given process. So multiple threads may belong to the same process.
By the way this is why synchronization is needed because these threads are using the same resources of the same process - such as memory.
Let's create 5 threads and then let's see the process which they belong to. This is why we need to import os (stands for operating system) module to be able to get the PID (Process ID) associated with the threads.
from threading import Thread
import os
class Counter(Thread):
def __init__(self, name):
Thread.__init__(self)
self.name = name
def run(self):
for i in range(10):
print('%s is running and belongs to process with ID %s' % (self.name, str(os.getpid())))
t1 = Counter('Thread #1')
t2 = Counter('Thread #2')
t3 = Counter('Thread #3')
t4 = Counter('Thread #4')
t5 = Counter('Thread #5')
t1.start()
t2.start()
t3.start()
t4.start()
t5.start()
And the result is that all the threads share the same process. Which means that all of these threads have the same Process ID (PID).
Thread #1 is running and belongs to process with ID 1788
Thread #2 is running and belongs to process with ID 1788
نظرات