线程锁实例2---读写加锁实例
来源:互联网 发布:地震科普知识网络竞赛 编辑:程序博客网 时间:2024/06/05 23:31
#include <stdio.h>#include <pthread.h>#include <unistd.h>struct student{int a ; int b ; int c ; int d ; int e ; int f ;};char stu[6] = {10,10,10,10,10,10};//初始化一个线程mutex锁 主要用途是防止资源访问竞争pthread_mutex_t Mutex = PTHREAD_MUTEX_INITIALIZER ; int write_stu(int value , const char *name);void read_stu(void);void *do_thread(void *arg);int main(void){pthread_t tid ; //struct student stu = {10,20};int ret ; ret = pthread_create(&tid , NULL , do_thread , (void *)100);//ret = pthread_create(&tid , NULL , do_thread , (void *)(&stu));if(ret < 0){perror("create thread fail");return -1 ; }ret = pthread_detach(tid);sleep(2);write_stu(80 , "main thread");return 0 ; }void *do_thread(void *arg){//写数据函数//写数据的时候加把锁,为了防止读和写同时进行write_stu(50 , "thread");//读数据函数read_stu();}int write_stu(int value , const char *name){//总共操作时间用6秒int i ; //给一个线程上锁//上锁,这时候只写pthread_mutex_lock(&Mutex);for(i = 0 ; i < 6 ; i++){stu[i] = value ; printf("%s write value:%d \n" , name , value);sleep(1);}//写完了,解锁pthread_mutex_unlock(&Mutex);}//读数据void read_stu(void){int i ; for(i = 0 ; i < 6 ; i++){printf("stu[%d] : %d \n" , i , stu[i]);}}
阅读全文
0 0
- 线程锁实例2---读写加锁实例
- 加锁实例
- 单实例模式 加锁
- 读写锁实例
- linux 读写锁应用实例
- 线程:实例2
- 单例模式加锁与不加锁实例C++
- 线程实例
- 线程实例
- 线程实例
- 线程 实例
- 线程实例
- mysql事务处理、加锁用法与实例详解
- SAP ABAP 加锁和解锁实例
- python线程锁实践实例
- 通用线程:Awk 实例 2
- 通用线程 -- sed 实例 2
- 读写锁ReadWriteLock和缓存实例
- Bellman-Ford算法
- D3.js制作二维坐标轴基本入门
- Tcp套接字
- MM自动记帐 -记账价值串-T156W表
- ALV中下拉列表列的实现
- 线程锁实例2---读写加锁实例
- pat-a 1107. Social Clusters (30)
- ny-86-找球号(一)
- transform—3D小练习
- 设计模式讲解与代码实践(七)——适配器(基于对象)
- laravel中,提交表单后给出提示例如添加成功,添加失败等等
- UNICODE与ASCII的区别
- Sumsets
- 使用UE4尝试复刻一个游戏