linux 多线程编程 互斥量
2018-02-04 17:26
330 查看
线程
互斥量
一 什么是互斥量互斥量是另一种用于多线程中的同步访问方法,它允许程序锁住某个对象,使得每次只能有一个线程访问它。为了控制对关键代码的访问,必须在进入这段代码之前锁住一个互斥量,然后在完成操作之后解锁。
二 互斥量函数的使用方法
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
pthread_mutex_lock和pthread_mutex_unlock都是原子操作,如果一个线程调用pthread_mutex_lock试图锁住互斥量,而该互斥量,又被其他线程锁住(占用),则该线程的pthread_mutex_lock调用就会阻塞,直到其他线程对该互斥量进行解锁,该线程才能获得该互斥量,pthread_mutex_lock调用才会返回。
三 例子
创建两个线程,每一个线程函数都是从0-9999对一个全局变量赋值,然后打印全局变量的值
/*
18.02.04
线程锁
*/
#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
pthread_mutex_t mutex;
int num = 0;
void * pthread_func1()
{
int i = 0;
pthread_mutex_lock(&mutex);
for(i=0; i < 10000; i++)
{
num=i;
printf("%s[%d], num=%d\n", __func__, __LINE__, num);
}
pthread_mutex_unlock(&mutex);
return 0;
}
void *pthread_func2()
{
int i = 0;
pthread_mutex_lock(&mutex);
for(i=0; i < 10000; i++)
{
num=i;
printf("%s[%d], num=%d\
4000
n", __func__, __LINE__, num);
}
pthread_mutex_unlock(&mutex);
return 0;
}
int main()
{
int iRet = 0;
pthread_t pid1;
pthread_t pid2;
pthread_mutex_init(&mutex, NULL);
iRet = pthread_create(&pid1, NULL, (void*)pthread_func1, NULL);
if(0 != iRet)
{
printf("---- pthread create fail, %d, %s\n", errno, strerror(errno));
}
iRet = pthread_create(&pid2, NULL, (void*)pthread_func2, NULL);
if(0 != iRet)
{
printf("----pthread create fail, %d, %s\n", errno, strerror(errno));
}
pthread_join(pid1, NULL);
pthread_join(pid2, NULL);
pthread_mutex_destroy(&mutex);
LEAVE:
return iRet;
}
打印的结果是,先打印出一个线程里0-9999的值,然后再打印出另一个线程0-9999的值
相关文章推荐
- linux多线程编程入门-同步机制-互斥量
- 《Linux 多线程服务端编程:使用 muduo C++ 网络库》电子版上市
- linux 下多线程epoll编程 -socket
- Linux下简单的多线程编程--线程池的实现
- linux 多线程编程---- 信号量的使用
- posix多线程有感--线程高级编程(互斥量属性)(代码)
- Linux多线程编程之基础篇
- 赖勇浩:推荐《Linux 多线程服务器端编程》
- Linux多线程编程之同步对象编程:线程信号量
- 基于Linux的消息队列及多线程编程实现的聊天室(一)
- Linux多线程编程小结
- (转)Linux 多线程编程---pthread_testcancel()等讲解
- 新书预告:《Linux 多线程服务端编程——使用 muduo C++ 网络库》
- Linux下的多线程编程
- 转【linux下多进程、多线程编程】
- Linux多线程编程入门-同步机制-条件变量
- Linux系统下的多线程编程入门二
- 基于Linux的消息队列及多线程编程实现的聊天室(一)
- linux C++多线程编程介绍
- Linux多线程编程基础