How can we implement multi-threading parallel processing?
In most programming languages, parallel processing can be achieved by creating multiple threads. Here is an example code demonstrating how to use multiple threads for parallel processing in Python.
import threading
def task1():
for i in range(5):
print("Task 1: {}".format(i))
def task2():
for i in range(5):
print("Task 2: {}".format(i))
if __name__ == "__main__":
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task2)
t1.start()
t2.start()
t1.join()
t2.join()
print("All tasks are done")
In this example, we have created two threads to execute functions task1 and task2. By calling the start() method, we begin the execution of the threads. We then use the join() method to wait for the threads to finish. Finally, we print “All tasks are done” to indicate that all tasks have been completed.
It is important to note that using multi-threading does not always improve performance, as threads require context switching and may result in resource competition. Therefore, it is important to use multi-threading cautiously and implement proper synchronization control for shared resources.