C語言讀寫鎖

#include <stdio.h>
#include <pthread.h>

int counter;
pthread_rwlock_t rwlock;

//3個線程不定時寫同一全局資源,5個線程不定時讀同一全局資源
void *th_write(void *arg)
{
    int t;
    while (1) 
    {    ///互斥量
        pthread_rwlock_wrlock(&rwlock);
        t = counter;
        ///sleep(1);
        printf("write %x : counter=%d ++counter=%d\n", (int)pthread_self(), t, ++counter);
        pthread_rwlock_unlock(&rwlock);
        usleep(100);
    }
}
void *th_read(void *arg)
{
    while (1) 
    {    ///共享
        pthread_rwlock_rdlock(&rwlock);
        printf("read %x : %d\n", (int)pthread_self(), counter);
        pthread_rwlock_unlock(&rwlock);
        usleep(100);
    }
}

int main(void)
{
    int i;
    pthread_t tid[8];
    pthread_rwlock_init(&rwlock, NULL);

    for (i = 0; i < 3; i++)
    {
        pthread_create(&tid[i], NULL, th_write, NULL);
    }

    for (i = 0; i < 5; i++)
    {
        pthread_create(&tid[i+3], NULL, th_read, NULL);
    }

    pthread_rwlock_destroy(&rwlock);

    for (i = 0; i < 8; i++)
    {
        pthread_join(tid[i], NULL);
    }

    return 0;
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章