【PTHREAD】线程互斥与同步之自旋锁

1 自旋锁类型

typedef volatile int pthread_spinlock_t;

2 初始化与销毁自旋锁

int pthread_spin_init(pthread_spinlock_t *lock, int pshared);
int pthread_spin_destroy(pthread_spinlock_t *lock);
  • PTHREAD_PROCESS_PRIVATE
  • PTHREAD_PROCESS_SHARED

3 自旋锁的加锁解锁

int pthread_spin_lock(pthread_spinlock_t *lock);
int pthread_spin_trylock(pthread_spinlock_t *lock);
int pthread_spin_unlock(pthread_spinlock_t *lock);

4 案例:自旋锁的使用

  • 源码

    #include 
    #include 
    #include 
    #include 
    #include 
    
    pthread_spinlock_t spinlock;
    
    void *start_routine_01(void *ptr)
    {
        printf("子线程(%lu)开始运行...\n", pthread_self());
        for (size_t i = 0; i < 3; i++)
        {
            pthread_spin_lock(&spinlock);
            printf("子线程(%lu)进入自旋锁\n", pthread_self());
            sleep(1);
            printf("子线程(%lu)离开自旋锁\n", pthread_self());
            pthread_spin_unlock(&spinlock);
        }
        return (void*)"9999";
    }
    
    void *start_routine_02(void *ptr)
    {
        printf("子线程(%lu)开始运行...\n", pthread_self());
        for (size_t i = 0; i < 3; i++)
        {
            pthread_spin_lock(&spinlock);
            printf("子线程(%lu)进入自旋锁\n", pthread_self());
            sleep(1);
            printf("子线程(%lu)离开自旋锁\n", pthread_self());
            pthread_spin_unlock(&spinlock);
        }
        return (void*)"9999";
    }
    
    int main(int argc, char const *argv[])
    {
        printf("主线程(%lu)开始运行...\n", pthread_self());
    
        pthread_spin_init(&spinlock, PTHREAD_PROCESS_PRIVATE);
        
        pthread_t thread_id_01;
        pthread_create(&thread_id_01, NULL, start_routine_01, NULL);
    
        pthread_t thread_id_02;
        pthread_create(&thread_id_02, NULL, start_routine_02, NULL);
    
        pthread_join(thread_id_01, NULL);
        pthread_join(thread_id_02, NULL);
    
        pthread_spin_destroy(&spinlock);
        printf("主线程(%lu)即将退出...\n", pthread_self());
        exit(EXIT_SUCCESS);
    }
    
  • 输出

    主线程(139684168165184)开始运行…
    子线程(139684168161024)开始运行…
    子线程(139684168161024)进入自旋锁
    子线程(139684159768320)开始运行…
    子线程(139684168161024)离开自旋锁
    子线程(139684168161024)进入自旋锁
    子线程(139684168161024)离开自旋锁
    子线程(139684168161024)进入自旋锁
    子线程(139684168161024)离开自旋锁
    子线程(139684159768320)进入自旋锁
    子线程(139684159768320)离开自旋锁
    子线程(139684159768320)进入自旋锁
    子线程(139684159768320)离开自旋锁
    子线程(139684159768320)进入自旋锁
    子线程(139684159768320)离开自旋锁
    主线程(139684168165184)即将退出…

你可能感兴趣的:(#,PTHREAD,开发语言,pthread)