您的位置:首页 > 运维架构 > Linux

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的值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: