pthread:使用互斥锁和自旋锁进行混合锁定

时间:2017-12-08 11:05:45

标签: c pthreads mutex spinlock

早上好。我认为混合互斥锁和自旋锁会加快锁定过程。因此,我试图通过混合互斥锁和旋转锁来创建混合锁。以下是我编写代码时的想法。

  1. 等待锁定获取,旋转1秒钟并等待锁定。
  2. 如果1秒后未获取锁定,则阻止该线程。
  3. 锁定优先于块状态的线程。
  4. 我的代码如下,但无法正常工作。

    struct hybrid_lock {
        pthread_mutex_t m_lock;
        pthread_spinlock_t s_lock;
    };
    
    int hybrid_lock_init(struct hybrid_lock *h_lock) {
        if(pthread_mutex_init(&h_lock->m_lock, NULL) != 0) {
            printf("mutex_init error.\n");
            return -1;
        }
        if(pthread_spin_init(&h_lock->s_lock, PTHREAD_PROCESS_PRIVATE) != 0) {
            printf("spin_init error.\n");
            return 0;
        }
    
        return 0;
    }
    
    int hybrid_lock_destroy(struct hybrid_lock *h_lock) {
        if(pthread_mutex_destroy(&h_lock->m_lock) != 0) {
            printf("mutex_destroy error.\n");
            return -1;
        }
        if(pthread_spin_destroy(&h_lock->s_lock) != 0) {
            printf("spin_destroy error.\n");
            return -1;
        }
    
        return 0;
    }
    
    int hybrid_lock_lock(struct hybrid_lock *h_lock) {
        struct timeval start, end;
        gettimeofday(&start, NULL);
        gettimeofday(&end, NULL);
    
        while(!(end.tv_sec > start.tv_sec && end.tv_usec > start.tv_usec)) {
            if(pthread_spin_trylock(&h_lock->s_lock) == 0) {
                return 0;
            }
            gettimeofday(&end, NULL);
        }
    
        pthread_mutex_lock(&h_lock->m_lock);
        return 0;
    }
    
    int hybrid_lock_unlock(struct hybrid_lock *h_lock) {
        pthread_spin_unlock(&h_lock->s_lock);
        pthread_mutex_unlock(&h_lock->m_lock);
    
        return 0;
    }
    

    你能否指出错误的部分?

    谢谢。祝你有愉快的一天!

0 个答案:

没有答案