简体   繁体   English

pthread rwlock从不同的线程锁定/解锁

[英]pthread rwlock lock/unlock from different threads

The docs says that locking from a thread and unlocking from another a rwlock results in undefined behaviour. 文档说从一个线程锁定并从另一个rwlock解锁会导致未定义的行为。 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. 问题是读/写线程仍然尝试在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. 我正在考虑为读/写线程使用读锁定并锁定数组以在dealloc线程中写入并解锁在alloc线程中写入。 But this results in undefined behavior since they happen on different threads. 但是这会导致未定义的行为,因为它们发生在不同的线程上。 What would be the right approach in this case? 在这种情况下,什么是正确的方法?

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. 因此,当线程需要检查或更改状态时,它会获取锁,检查或更改状态,然后释放锁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM