How to close all windows if one of them is closed?

exit your program using a key, such as ESC, or any key really. detect that by checking waitKey's result.

OpenCV’s highgui doesn’t pass window closing events along, so it is a bad idea to close imshow windows using the [X] button or Alt+F4.