Linux多线程编程学习代码(代码已上传gitee,还请各位兄弟点个Star哦!)
https://gitee.com/chenshao777/linux_thread.git
笔记:
1.读写锁可以避免同一时刻只有一个线程对变量有使用权
phread_rwlock_init()
2.读写锁有三种状态,读加锁、写加锁、不加锁
3.读加锁时,其他线程都可以占用读模式的读写锁
如果此时有线程以写模式对其进行加锁,则会阻塞,而且后来的读模式加锁也会阻塞,防止写锁请求失败
4.写加锁时,线程独占读写锁,其他线程的读写锁请求都会阻塞
5.读加锁模式下,若线程希望写加锁,则会阻塞,直到所有线程释放锁为止
6.读写锁非常适合经常需要读动作的程序
读模式加锁
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_tryrdlock(pthread_rwlock_t "rwlock); //尝试加读模式锁,失败则不阻塞
写模式加锁
int pthread_rwlock_wrlock(pthread_rwlock_t "rwlock);
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
解锁
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
销毁
pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
成功返回0
spu.h文件
#ifndef _SPU_H_
#define _SPU_H_
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<signal.h>
#include<errno.h>
#endif
09.thread_rwlock.c文件
/*
1.创建三个线程,都对 money 全局变量进行操作
2.线程1每次对 money 加10
3.线程2每次对 money 加0.01
4.线程3读取 money 的值
*/
#include "spu.h"
float money;
//定义读写锁
pthread_rwlock_t rwlock;
void *thread_fun1(void *arg)
{
while(1)
{
pthread_rwlock_wrlock(&rwlock); //加写锁
money += 10;
printf("01: money = %.2f\n",money);
pthread_rwlock_unlock(&rwlock); //解锁
usleep(500000); //500ms延时
}
return (void*)1;
}
void *thread_fun2(void *arg)
{
while(1)
{
pthread_rwlock_wrlock(&rwlock); //加写锁
money += 0.01;
printf("02: money = %.2f\n",money);
pthread_rwlock_unlock(&rwlock); //解锁
usleep(500000);
}
return (void*)2;
}
void *thread_fun3(void *arg)
{
while(1)
{
pthread_rwlock_rdlock(&rwlock); //加读锁
printf("03: reade money = %.2f\n",money);
pthread_rwlock_unlock(&rwlock); //解锁
usleep(500000); //500ms延时
}
return (void*)3;
}
int main(int argc, char *argv[])
{
int err1, err2, err3;
pthread_t thread_id1, thread_id2, thread_id3;
void *__retval;
//首先初始化读写锁
pthread_rwlock_init(&rwlock, NULL);
err1 = pthread_create(&thread_id1, NULL, thread_fun1, NULL);
if(err1 != 0)
printf("create thread01 failed!\n");
err2 = pthread_create(&thread_id2, NULL, thread_fun2, NULL);
if(err2 != 0)
printf("create thread02 failed!\n");
err3 = pthread_create(&thread_id3, NULL, thread_fun3, NULL);
if(err3 != 0)
printf("create thread03 failed!\n");
sleep(1);
pthread_exit(__retval);
}