在一个线程中锁定互斥锁,在另一个线程中解锁互斥锁
此代码正确且可移植吗?
Will this code be correct and portable?
void* aThread(void*)
{
while(conditionA)
{
pthread_mutex_lock(mutex1);
//do something
pthread_mutex_unlock(mutex2);
}
}
void* bThread(void*)
{
while(conditionB)
{
pthread_mutex_lock(mutex2);
//do something
pthread_mutex_unlock(mutex1);
}
}
在实际的应用程序中,我有三个线程-两个用于将值添加到数组中,另一个用于读取它们.而且我需要第三个线程在其他线程之一添加新项之后立即显示数组的内容.
In the actual application I have three threads - two for adding values to an array and one for reading them. And I need the third thread to display the contents of the array right after one of the other threads adds a new item.
不是.如果线程A在线程B到达Mutex_lock(2)之前到达了Mutex_unlock(2),则您将面临未定义的行为.您也不能解锁另一个线程的互斥锁.
It is not. If thread A gets to mutex_unlock(2) before thread B got to mutex_lock(2), you are facing undefined behavior. You must not unlock another thread's mutex either.
pthread_mutex_lock开放组基本规范这样说:>
The pthread_mutex_lock Open Group Base Specification says so:
如果互斥锁类型为PTHREAD_MUTEX_NORMAL [...]如果线程尝试解锁尚未锁定的互斥锁或已解锁的互斥锁,则会导致未定义的行为.
If the mutex type is PTHREAD_MUTEX_NORMAL [...] If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, undefined behavior results.