* @brief Locks a mutex. * * This function locks the mutex object pointed to by `mutex`. If the mutex is * already locked by another thread, the calling thread will block until the * mutex becomes available. * * @param[in,out] mutex Pointer to the mutex to be locked. * * @return * - 0 on success. * - Non-zero error code on failure, including: * - `EDEADLK`: A deadlock condition was det
| 392 | * @see pthread_mutex_unlock, pthread_mutex_trylock, pthread_mutex_init |
| 393 | */ |
| 394 | int pthread_mutex_lock(pthread_mutex_t *mutex) |
| 395 | { |
| 396 | int mtype; |
| 397 | rt_err_t result; |
| 398 | |
| 399 | if (!mutex) |
| 400 | return EINVAL; |
| 401 | |
| 402 | if (mutex->attr == -1) |
| 403 | { |
| 404 | /* init mutex */ |
| 405 | pthread_mutex_init(mutex, RT_NULL); |
| 406 | } |
| 407 | |
| 408 | mtype = mutex->attr & MUTEXATTR_TYPE_MASK; |
| 409 | rt_enter_critical(); |
| 410 | if (mutex->lock.owner == rt_thread_self() && |
| 411 | mtype != PTHREAD_MUTEX_RECURSIVE) |
| 412 | { |
| 413 | rt_exit_critical(); |
| 414 | |
| 415 | return EDEADLK; |
| 416 | } |
| 417 | rt_exit_critical(); |
| 418 | |
| 419 | result = rt_mutex_take(&(mutex->lock), RT_WAITING_FOREVER); |
| 420 | if (result == RT_EOK) |
| 421 | return 0; |
| 422 | |
| 423 | return EINVAL; |
| 424 | } |
| 425 | RTM_EXPORT(pthread_mutex_lock); |
| 426 | |
| 427 | /** |