思路: linux多线程时,数据空间为公共,一个线程去添加数据,一个线程去修改数据,这个时候需要加入互斥锁,俩个线程如果同时去处理这个数据空间,数据会出错,除了线程锁之外,学习了一个读写锁
详细函数说明: https://www.cnblogs.com/x_wukong/p/5671537.html
核心函数:
初始化读写锁 pthread_rwlock_init
写入读写锁中的锁 pthread_rwlock_wrlock(阻塞)
解除锁定读写锁 pthread_rwlock_unlock
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
char tmp_buf[100] = { 0 };
void test()
{
time_t now_time = 0;
while (1)
{
pthread_rwlock_wrlock(&rwlock);
now_time = time(NULL);
snprintf(tmp_buf, sizeof(tmp_buf) - 1, "%ld", now_time);
printf("test : %s\n", tmp_buf);
pthread_rwlock_unlock(&rwlock);
sleep(2);
}
}
int main()
{
int ret = pthread_rwlock_init(&rwlock, NULL);
pthread_t fp;
if (ret != 0)
{
printf("creat err!\n");
}
if ((pthread_create(&fp, NULL, (void *)&test, NULL)) == -1)
{
printf("create error!\n");
return 1;
}
while (1)
{
pthread_rwlock_wrlock(&rwlock);
snprintf(tmp_buf, sizeof(tmp_buf) - 1, "test");
sleep(5);
printf("main : %s\n", tmp_buf);
pthread_rwlock_unlock(&rwlock);
sleep(1);
}
}
gcc test_time.c -lpthread -o hello
结果:
不加锁
./hello
test : 1564587467
test : 1564587469
test : 1564587471
main : 1564587471
test : 1564587473
test : 1564587475
test : 1564587477
main : 1564587477
test : 1564587479
test : 1564587481
加锁
./hello
main : test
test : 1564587516
main : test
test : 1564587522
main : test
test : 1564587528