问题描述
我正在研究一些描述互斥量和二进制信号量之间差异的主题.在许多主题中都指出,信号量充当信号机制,即,如果线程已锁定信号量,则另一个线程可以解锁(释放)信号量(充当信号).但是对于互斥锁,只有锁定该互斥锁的线程才能对其进行解锁.其他任何线程都无法对其进行解锁,如果其他线程试图对其进行解锁,则会返回错误.
I was looking over some topics that describes the difference between mutex and binary semaphore. In many topics it is stated that semaphore act as a signalling mechanism i.e if a thread has locked a semaphore then another thread can unlock(release) the semaphore(acting as signal).But in case of mutex only the thread that locks the mutex can unlock it .It can't be unlocked by any other thread and if other thread tries to unlock it this will return error.
我尝试编写使用互斥量进行同步的代码.在代码中,我将互斥锁锁定在一个线程中,并成功将互斥锁解锁在另一个线程中.有人可以解释一下这是怎么发生的.根据其他地方的答案,其他线程都不能解锁互斥体.
I have tried writing a code that uses mutex for synchronization. In the code I am locking the mutex in one thread and successfully unlocking the mutex in other thread.Can someone please explain how this can happen.According to the answers everywhere the other thread should not be able to unlock mutex.
任何建议都是最欢迎的.
Any suggestions are most welcome.
推荐答案
根据pthread_mutex_lock手册页:如果互斥锁类型为PTHREAD_MUTEX_DEFAULT,则尝试解锁互斥锁(如果未被调用线程锁定)会导致未定义行为.如果未锁定互斥锁,则尝试对其进行解锁会导致未定义的行为.
According to pthread_mutex_lock man page: If the mutex type is PTHREAD_MUTEX_DEFAULT, attempting to unlock the mutex if it was not locked by the calling thread results in undefined behavior. Attempting to unlock the mutex if it is not locked results in undefined behavior.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <errno.h>
#include <syscall.h>
pthread_mutex_t mutex;
void *thread(void *ptr)
{
int ret = pthread_mutex_unlock(&mutex);
if (!ret)
{
printf("error unlocking: %s", strerror(errno));
}
printf("tid: %u - owner: %u\n", syscall(SYS_gettid), mutex.__data.__owner);
return NULL;
}
int main()
{
pthread_t thread1;
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
pthread_mutex_init(&mutex, &attr);
pthread_mutexattr_destroy(&attr);
pthread_mutex_lock(&mutex);
printf("tid: %u - owner: %u\n", syscall(SYS_gettid), mutex.__data.__owner);
pthread_create(&thread1, NULL, thread, NULL);
pthread_join(thread1, NULL);
return 0;
}
对我来说是输出
tid: 13987 - owner: 13987
tid: 13992 - owner: 13987
互斥量和二进制信号量之间的唯一区别是所有者概念. Mutex有一个所有者,因此您必须在同一线程中"对其进行锁定和解锁,但是您可以在不同线程中发布或等待信号量.
The sole difference between mutex and binary semaphore is the owner concept. Mutex has an owner, so you "must" lock and unlock it in the same thread, but you can post or wait semaphore in different threads.
这篇关于信号量信号与互斥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!