线程之互斥锁
来源:互联网 发布:c语言flag 编辑:程序博客网 时间:2024/06/14 18:14
在多线程中对共享资源的访问
在一个多线程的程序中,有时需要同时对共享资源的访问,就会造成对共享资源的读写问题。
例如:有五个线程,其中一个对共享资源进行修改,其余四个线程需要同时对共享资源进行读访问。势必会造成其余四个线程读取数据的不稳定。此时就可以使用互斥锁去解决这一问题。
当修改共享资源的线程需要对数据进行修改时,首先得到互斥锁,进行加锁。其他进程就被阻塞不可以去读取资源了。操作完成后,解锁,其他线程就可以对资源进行访问了。
关于互斥锁的操作有以下步骤:
1、初始化互斥锁
pthread_mutex_init(&mutex,NULL);
2、对操作的数据加锁
pthread_mutex_lock(&mutex); “`
3、对操作的数据解锁
pthread_mutex_unlock(&mutex);
4、销毁互斥锁
pthread_mutex__destroy(&mutex); “
`
#include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h>//目的创建多个线程,一个对共享资源进行修改,四个对共享资源进行访问#if 0int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);int pthread_join(pthread_t thread, void **retval);#endifchar name[] = "hello,world!";pthread_mutex_t mutex;void *start_routine_read(void *arg){ while(1) { pthread_mutex_lock(&mutex); printf("@%d,%s\n",pthread_self(),name); pthread_mutex_unlock(&mutex); sleep(1); } return (void *)0;}void *start_routine_write(void *arg){ while(1) { pthread_mutex_lock(&mutex); char temp_str[12] = ""; printf("input string:"); scanf("%s",temp_str); strcpy(name,temp_str); printf("@%d,write data:%s\n",pthread_self(),name); pthread_mutex_unlock(&mutex); sleep(1); } return (void *)0; }int main(void){ pthread_t thread[5]; int i = 0; pthread_mutex_init(&mutex,NULL); //创建5个线程 for(i = 1;i < 5;i++) { pthread_create(thread+i,NULL,start_routine_read,NULL); } pthread_create(thread,NULL,start_routine_write,NULL); while(1); pthread_mutex_destroy(&mutex); //回收线程资源 for(i = 1;i < 5;i++) { pthread_join(thread[i],NULL); } pthread_join(thread[0],NULL); return 0;}
代码中尚有不完善指出,请指出,谢谢!
0 0
- 线程同步之互斥锁
- 线程之互斥锁
- 线程同步之互斥锁
- Linux线程同步之互斥锁
- ACE线程之ACE_Thread_Mutex互斥锁
- linux线程同步之互斥锁
- 线程之互斥锁与死锁
- 线程之线程终止
- 线程之线程同步
- 线程之守护线程
- Linux线程编程 - 线程同步机制之互斥锁
- 线程间同步 之 互斥锁 mutex
- Linux--16:Linux线程之互斥锁pthread_mutex_t
- 喜羊羊系列之【 线程 】互斥锁+信号量
- linux多线程编程---线程同步之互斥锁
- Linux编程之互斥锁线程控制
- Windows线程同步之互斥锁(Mutex)
- 线程同步之互斥锁(互斥量)
- Atitit hre框架v5 新特性 HREv5
- jQuery的deferred对象和promise对象
- Atitit. atiJavaExConverter4js 新的特性
- python 数据分析环境安装
- Atitit. Xss 漏洞的原理and应用xss木马
- 线程之互斥锁
- Atitit.视频文件加密的方法大的总结 java c# php
- 使用GPG学习非对称加密
- foreach
- 浅谈游戏服务器开发-地图描述
- 九、排序算法的应用(找中位数、重复统计、Kendall tau距离等)
- HDU 2717 Catch That Cow(BFS)
- 实现Ogre的脚本分离 - 天龙八部的源码分析(一)
- 深入jar包:从jar包中读取资源文件