Learning Professional Python by Bhimavarapu Usharani;Hemanth Jude D.; & Jude D. Hemanth

Learning Professional Python by Bhimavarapu Usharani;Hemanth Jude D.; & Jude D. Hemanth

Author:Bhimavarapu, Usharani;Hemanth, Jude D.; & Jude D. Hemanth
Language: eng
Format: epub
Publisher: CRC Press LLC
Published: 2024-10-15T00:00:00+00:00


Output

test run() 0

test run() 1

test run() 2

test run() 3

test run() 4

sample run() 0

sample run() 1

sample run() 2

sample run() 3

sample run() 4

In the preceding program the join() method is used, which blocks the remaining threads until the current thread completes its task.

5.4 Synchronizing the Thread

In Python, a lock is started by invoking the lock() method, which returns the new lock. The release() method of the new lock object is exploited to release the lock when it is no longer needed.

import threading

import os

def test1():

print(“test 1 assigned to thread: {}”.format(threading.current_thread().name))

print(“ID of process running test 1: {}”.format(os.getpid()))

def test2():

print(“test 2 assigned to thread: {}”.format(threading.current_thread().name))

print(“ID of process running test 2: {}”.format(os.getpid()))

if __name__ == “__main__”:

# print ID of current process

print(“ID of process running main program: {}”.format(os.getpid()))

# print name of main thread

print(“Main thread name: {}”.format(threading.current_thread().name))

# creating threads

t1 = threading.Thread(target=test1, name=‘t1’)

t2 = threading.Thread(target=test2, name=‘t2’)

# starting threads

t1.start()

t2.start()

# wait until all threads finish

t1.join()

t2.join()



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.