Junior — Middle
Can you explain what process or thread competition is in programming?
sobes.tech AI
Answer from AI
Process or thread competition is a situation where multiple processes or threads run simultaneously and may access shared resources.
In programming, this is important for improving performance and resource utilization but requires management to avoid conflicts, such as data races.
Example: two threads try to modify the same variable at the same time. Without synchronization, the result can be unpredictable.
In Python, competition is achieved using threads (threading) or processes (multiprocessing). Threads share memory, processes do not.
Example with threads:
import threading
counter = 0
def increment():
global counter
for _ in range(100000):
counter += 1
thread1 = threading.Thread(target=increment)
thread2 = threading.Thread(target=increment)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print(counter) # The result may be less than expected due to data races
To work correctly, locks (Lock) are used to prevent competition issues.