Reputation: 575
I was using threading
module with OpenCV, I came accross a bizarre issue. When using thread I was unable to start the camera again to take video input. I would take one frame and then stop. While there was no problem like this when using multiprocessing
module. I am unable to understand what causes this strange behaviour.
This code summarizes the problem I have, The program will stuck when the thread is created second time.
import cv2
import time
import threading
def open_cam():
count = 0
cam = cv2.VideoCapture(0)
while True:
ret_val, img = cam.read()
print(ret_val)
cv2.imshow("Image", img)
count += 1
if count == 100:
break
if (cv2.waitKey(1) & 0xFF) == ord('q'):
break
cv2.destroyAllWindows()
def start_thread():
print("CREATING THREAD")
cam_thread = threading.Thread(target=open_cam)
print("STARTING THREAD")
cam_thread.start()
start_thread()
time.sleep(5)
start_thread()
However, This code works exactly how I desire, This uses multiprocessing
module instead of threading
import cv2
import time
import multiprocessing
def open_cam():
count = 0
cam = cv2.VideoCapture(0)
while True:
ret_val, img = cam.read()
print(ret_val)
cv2.imshow("Image", img)
count += 1
if count == 100:
break
if (cv2.waitKey(1) & 0xFF) == ord('q'):
break
cv2.destroyAllWindows()
def start_process():
print("CREATING process")
cam_process = multiprocessing.Process(target=open_cam)
print("STARTING process")
cam_process.start()
start_process()
time.sleep(5)
start_process()
What is the root cause of the problem and How can I fix it?
Upvotes: 2
Views: 3493
Reputation: 4561
This is caused by the Global Interpreter Lock. Threads share the program memory. To protect against conflicts caused by separate threads changing the same variable, Python locks execution to a specific thread. Meaning that at any moment only one thread runs. When the CPU is idle the program switches between threads, making IO-bound applications run faster. By contrast, Processes run simultaneously on separate cores and do not share memory.
When the second thread starts in your code, both Threads try to access the same variables. This causes the error with threads, while processes run fine.
Here is excellent and more lengthy explanation.
Upvotes: 3