create_mutex( : : AttribName, AttribValue : MutexHandle)
A mutex is a synchronization object that negotiates mutual exclusion among threads of a single process to avoid simultaneous modifications on common resources such as global variables. A mutex has two possible states: unlocked, i.e., not owned by any thread, and locked, i.e., owned by one certain thread. Threads attempting to lock a mutex that is already owned by another thread, i.e., locked, wait until the owning thread unlocks the mutex first. Unlike events, a thread has to own a mutex to unlock it.
create_mutex allocates and initializes the mutex object according to the attributes specified in AttribName and AttribValue. AttribName specifies the attribute class and AttribValue the kind of the mutex. The description beneath lists all mutex kinds supported by following classes:
”
empty string sets the default attributes.
‘type’
specifies what happens if a thread attempts to lock a mutex that is already owned:
‘sleep’
普通非迭代互斥锁。休眠调用线程如果锁未释放(default),如果调用线程是锁的所有者,行为不能确定。
‘spin’
自旋锁。调用线程忙等待直到锁释放, 如果调用线程是锁的所有者,行为不能确定。
‘recursive’
迭代互斥锁。休眠调用线程如果锁未释放。锁的所有者线程可以多次获取该递归锁,不会产生死锁。只有当解锁次数等于上锁次数时,锁释放。
try_lock_mutex( : : MutexHandle : Busy)
调用线程尝试给mutex上锁。先查询Mutex状态赋值给Busy变量。如果mutex未释放,则立刻返回。
lock_mutex( : : MutexHandle : )
调用线程给mutex上锁,如果mutex未释放,则按之前create_mutex中指定的方式等待。
互斥量的加锁和解锁必须由同一线程分别对应使用
本文详细介绍了互斥锁的创建与使用方法,包括如何通过create_mutex分配和初始化互斥锁对象,并根据不同的属性设置(如普通非迭代、自旋锁及迭代互斥锁)来实现线程间的同步。此外还解释了lock_mutex与try_lock_mutex等函数的作用。

251

被折叠的 条评论
为什么被折叠?



