Read locks can nest, but writable locks cannot. The code here could have called VecLockWriteSet(y, PETSC_TRUE) and then released it. Arguably that would be more correct, though it does require a matching line of code and the writable access does not outlive the function. It also would the x == y logic to be reworked because the simpler functions can't be called when a write lock is held.
IMO, it would be great if the compiler could enforce that arguments are not aliased, but C doesn't provide a way to do that and forbidding it would have ripple effects. Satish Balay <[email protected]> writes: > I see the initial change was at: > > https://urldefense.us/v3/__https://gitlab.com/petsc/petsc/-/commit/d9ca1df42eda25bc875149d6d493aad6e204c9ff__;!!G_uCfscf7eWS!axSTcfB_iW7kKJe0hb14ApkNvXzHZBDqzONfz8eP0TVZNPqaBKoS2fxZhoUWUBKQk8RQpEVrly41e_Pt-04eizfoQw$ > > > And then refined at: > > https://urldefense.us/v3/__https://gitlab.com/petsc/petsc/-/commit/8860a1345bb13588f3290163e72ce904901dbfb9__;!!G_uCfscf7eWS!axSTcfB_iW7kKJe0hb14ApkNvXzHZBDqzONfz8eP0TVZNPqaBKoS2fxZhoUWUBKQk8RQpEVrly41e_Pt-04ysS1gxw$ > > > Satish > > On Mon, 8 Sep 2025, Hovland, Paul via petsc-dev wrote: > >> Dear PETSc developers: >> >> We have a question about the (expected) use of read and write locks in the >> PETSc implementation of vectors. If one looks at the implementation of >> VecAXPY in rvector.c (or, really, the implementation of >> VecAXPYAsync_Private, which is called by VexAXPY), it first calls >> PetscCall(VecSetErrorIfLocked(y, 1)); >> then calls >> PetscCall(VecLockReadPush(x)); >> then dispatches the AXPY method, followed by >> PetscCall(VecLockReadPop(x)); >> >> We’re curious why it just checks whether y is locked but goes through the >> whole locking and unlocking process for x. It seems like one should either >> also lock y or one could simply check whether there is a write lock on x, >> without having to go through the whole push/pop sequence. >> >> Is it written this way because the easiest way to check whether x has a >> write lock on it (and throw an error if it does) is to call >> VecLockReadPush? Is this pattern a relic of when PETSc implemented locks >> differently? Is there some other reason for the “inconsistent” (to our >> minds) handling of x and y? >> >> Thanks, >> >> Paul & Steve >>
