The docs says that locking from a thread and unlocking from another a rwlock results in undefined behaviour. I have an array and two threads, one allocating it and one deallocating it, this happens in a cycle, and there are also some threads reading/writing in it, but they never overlap so no synchronization is needed there. The problem is the read/write threads still try to use the array in the timeframe between dealloc - alloc. I was thinking of using a read lock for the read/write threads and lock the array for writing in the dealloc thread and unlocking writing in alloc thread. But this results in undefined behavior since they happen on different threads. What would be the right approach in this case?
Asked
Active
Viewed 566 times
1 Answers
3
You need some variable that stores the state. You can protect that variable with a lock. So when a thread needs to check or change the state, it acquires the lock, checks or changes the state, and then releases the lock.

David Schwartz
- 179,497
- 17
- 214
- 278
-
Yeah, I also think this is the only solution. I was trying to avoid checking the state every time I do a read/write. – Jelly Dec 18 '14 at 08:30
-
Doesn't this solution imply a busy-wait (vs. the [potential] blocking semantics of the rwlock)? – jhfrontz Aug 21 '15 at 16:29
-
You can use, for example, condition variables. – David Schwartz Aug 21 '15 at 16:35