53 lines
1.2 KiB
C
53 lines
1.2 KiB
C
|
#include <stdio.h>
|
|||
|
#include <pthread.h>
|
|||
|
#include <unistd.h>
|
|||
|
|
|||
|
// 定义读写锁(需要 GNU99)
|
|||
|
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER; // 静态初始化读写锁
|
|||
|
|
|||
|
void *read_task(void *data)
|
|||
|
{
|
|||
|
int *n = (int *)data;
|
|||
|
|
|||
|
while (1)
|
|||
|
{
|
|||
|
pthread_rwlock_rdlock(&rwlock); // 申请读锁 rdlock
|
|||
|
printf("(%ld)线程读取 num: %d\n", pthread_self(), *n);
|
|||
|
pthread_rwlock_unlock(&rwlock); // 解锁
|
|||
|
usleep(500 * 1000);
|
|||
|
}
|
|||
|
return NULL;
|
|||
|
}
|
|||
|
|
|||
|
void *write_task(void *data)
|
|||
|
{
|
|||
|
int *n = (int *)data;
|
|||
|
while (1)
|
|||
|
{
|
|||
|
pthread_rwlock_wrlock(&rwlock); // 申请写锁 wrlock
|
|||
|
(*n)++;
|
|||
|
printf("(%ld) 线程写 num: %d\n", pthread_self(), *n);
|
|||
|
pthread_rwlock_unlock(&rwlock); // 解锁
|
|||
|
sleep(2);
|
|||
|
}
|
|||
|
|
|||
|
return NULL;
|
|||
|
}
|
|||
|
|
|||
|
int main(int argc, char const *argv[])
|
|||
|
{
|
|||
|
int num; // 公共资源
|
|||
|
pthread_t t1, t2, t3;
|
|||
|
pthread_create(&t1, NULL, read_task, &num);
|
|||
|
pthread_create(&t2, NULL, read_task, &num);
|
|||
|
pthread_create(&t3, NULL, write_task, &num);
|
|||
|
|
|||
|
pthread_join(t1, NULL);
|
|||
|
pthread_join(t2, NULL);
|
|||
|
pthread_join(t3, NULL);
|
|||
|
|
|||
|
pthread_rwlock_destroy(&rwlock); // 销毁读写锁
|
|||
|
|
|||
|
return 0;
|
|||
|
}
|