Linux 同步机制:互斥量
来源:互联网 发布:linux udp服务器 编辑:程序博客网 时间:2024/06/12 00:24
互斥量与信号量对比
互斥量也叫互斥锁,也是Linux的一种同步机制。互斥量相比信号量增加了所有权的概念,被锁的互斥量只能由给它上锁的线程解开,而信号量则无此限制。信号量侧重在资源的数量,可用来实现按一定逻辑调度线程。互斥量则就是纯粹的保护共享资源,不被并发访问,用起来也更加的简单。
对于可以用互斥量解决的场景,就不要用信号量。
举例
下面是典型的生产者消费者例子,读写过程做到原子操作。编译的时候需要链接lpthread, gcc main.c -lpthread
.
#include <stdio.h>#include <string.h>#include <pthread.h>#include <unistd.h>char buff[100];pthread_mutex_t mutex;/* write, 整个写操作需要要做到原子 */void* thread1_main(void *p){ pthread_mutex_lock(&mutex); printf("thread1 --> write: "); strcat(buff, "hello, "); sleep(1); strcat(buff, "world!"); printf("%s\n", buff); pthread_mutex_unlock(&mutex);}/* read, 整个读操作需要要做到原子 */void* thread2_main(void *p){ pthread_mutex_lock(&mutex); while (1) { if (strlen(buff) > 0) { printf("thread2 --> read: %s\n", buff); break; } } pthread_mutex_unlock(&mutex);}int main(){ pthread_t tid1, tid2; void *ret1, *ret2; /* 简便起见,没有通过返回值没有判断下面的函数调用是否ok */ pthread_mutex_init(&mutex, NULL); pthread_create(&tid1, NULL, thread1_main, NULL); pthread_create(&tid2, NULL, thread2_main, NULL); pthread_join(tid1, &ret1); pthread_join(tid2, &ret2); pthread_mutex_destroy(&mutex); return 0;}
0 0
- Linux 同步机制:互斥量
- linux多线程编程入门-同步机制-互斥量
- linux 2.6同步机制
- linux线程同步机制
- Linux多线程同步机制
- Linux 内核同步机制
- Linux 内核同步机制
- Linux中的同步机制
- Linux内核 - 同步机制
- Linux多线程同步机制
- linux同步机制
- linux 同步机制
- linux内核同步机制
- Linux 内核同步机制
- Linux的同步机制
- Linux中的同步机制
- Linux Kernel同步机制
- linux 进程同步机制
- 递归
- 自定义View之Switch
- 一行一步一花新:python-0
- Springboot配置aop
- Spring Boot
- Linux 同步机制:互斥量
- 2016/12/26
- 蛇阵
- 知识库--ZooKeeper create Session (61)
- HttpWatch无法显示此页解决办法!
- Linux内核之进程管理
- SpringMVC工作原理
- 【学习总结】关于magin padding对block、inline、inline-block 元素的影响
- spring MVC原理