Add finishAndThrow function to ProcessGroup::Work, and use with Gloo (#40405)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/40405
This adds a finishAndThrow function that completes the work object,
sets an exception if one is provided by the user, and throws an exception (if
it is already set or passed by the caller). This is now done by grabbing the
lock just once and simplifies the wait functions in ProcessGroupGloo.
ghstack-source-id: 106516114
Test Plan: CI
Differential Revision: D22174890
fbshipit-source-id: ea74702216c4328187c8d193bf39e1fea43847f6