简体   繁体   English

如果在调用pthread_mutex_lock()时线程未成功执行该怎么办?

[英]What happens if a thread doesn't succeed when making a pthread_mutex_lock() call?

I'm doing a experiment, which, I think, is a guaranteed deadlock situation: 我正在做一个实验,我认为这是可以保证的死锁情况:

void *thread_1(void *vptr)
{
    pthread_mutex_lock(&a);
    sleep(1);
    pthread_mutex_lock(&b);
    pthread_mutex_unlock(&b);
    pthread_mutex_unlock(&a);
}

void *thread_2(void *vptr)
{
    pthread_mutex_lock(&b);
    sleep(1);
    pthread_mutex_lock(&a);
    pthread_mutex_unlock(&a);
    pthread_mutex_unlock(&b);
}

What happens if a thread cannot lock? 如果线程无法锁定怎么办? Does it get into a queue, waiting for the mutex, or does it simply move on to the next instruction? 它是否进入队列,等待互斥,还是只是继续执行下一条指令?

In your case both threads will be suspended forever waiting for the mutexes. 在您的情况下,两个线程将永远挂起,等待互斥。 If you start both threads at once. 如果您同时启动两个线程。

Why don't you just create the mutexes and the threads and then run your example? 为什么不创建互斥对象和线程,然后运行示例?

If a thread tries to lock a mutex that is already locked by another thread, it will be suspended. 如果一个线程试图锁定已被另一个线程锁定的互斥锁,它将被挂起。 In this case, its execution will not continue until it has acquired the lock. 在这种情况下,只有获得了锁,它的执行才会继续。 (There is no "queue" though - just an unordered set of waiting threads. Any waiting thread could be the next to acquire the mutex). (尽管没有“队列”-只是一组无序的等待线程。 任何等待线程都可以成为下一个获取互斥锁的线程)。

If a thread tries to lock a mutex that is already locked by itself or not initialised properly, then pthread_mutex_lock() may return a non-zero error code, and execution will continue without the mutex being acquired. 如果线程试图锁定已被自身锁定或未正确初始化的互斥锁,则pthread_mutex_lock()可能返回非零错误代码,并且执行将继续进行 ,而不会获取该互斥锁。

It depends on the reason why it couldn't lock. 这取决于它无法锁定的原因。 Eg if the thread already holds the lock, an error might be returned. 例如,如果线程已持有锁,则可能返回错误。 You should check the return value, anyhow, and check the manual page for the error codes that are return in errno . 无论如何,您应该检查返回值,并检查手册页中errno中返回的错误代码。 Mine (linux) states: 我的(linux)指出:

  The pthread_mutex_lock() function may fail if: EDEADLK The current thread already owns the mutex. 

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

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