1.互斥锁概念:
在编程中,引入了对象互斥锁的概念,来保证共享数据操作的完整性。每个对象都对应于一个可称为" 互斥锁" 的标记,这个标记用来保证在任一时刻,只能有一个线程访问该对象。
2.常用函数
互斥锁参数类型 -- pthread_mutex_t mutex
互斥锁初始化 -- pthread_mutex_init
表头文件 | #include <pthread.h> |
定义函数 | int pthread_mutex_init( pthread_mutex_t *mutex, const pthread_mutex_attr_t* attr ); |
函数说明 | 该函数初始化一个互斥体变量,如果参数attr 为NULL,则互斥体变量mutex 使用默认的属性。 |
返回值 |
销毁互斥锁 -- pthread_mutex_destroy
表头文件 | #include <pthread.h> |
定义函数 | int pthread_mutex_destroy ( pthread_mutex_t *mutex ); |
函数说明 | 该函数用来释放分配给参数mutex 的资源。 |
返回值 | 调用成功时返回值为 0, 否则返回一个非0 的错误代码。 |
加锁 -- pthread_mutex_lock
表头文件 | #include <pthread.h> |
定义函数 | int pthread_mutex_lock( pthread_mutex_t *mutex ); |
函数说明 | 该函数用来锁住互斥体变量。如果参数mutex 所指的互斥体已经被锁住了,那么发出调用的线程将被阻塞直到其他线程对mutex 解锁。 |
返回值 |
尝试加锁,失败返回不阻塞 -- pthread_mutex_trylock
表头文件 | #include <pthread.h> |
定义函数 | int pthread_mutex_trylock( pthread_t *mutex ); |
函数说明 | 该函数用来锁住mutex 所指定的互斥体,但不阻塞。 |
返回值 | 如果该互斥体已经被上锁,该调用不会阻塞等待,而会返回一个错误代码。 |
解锁 -- pthread_mutex_unlock
表头文件 | #include <pthread.h> |
定义函数 | int pthread_mutex_unlock( pthread_mutex_t *mutex ); |
函数说明 | 该函数用来对一个互斥体解锁。如果当前线程拥有参数mutex 所指定的互斥体,该调用将该互斥体解锁。 |
返回值 |
#include <iostream>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
using namespace std;
#define MAX 10000
int number;
//创建一把互斥锁
pthread_mutex_t mutex;
void* funcA_num(void* arg) {
for (int i = 0; i < MAX; ++i) {
//访问全局变量前加锁
pthread_mutex_lock(&mutex);
int cur = number;
cur++;
number = cur;
cout << "Thread A,id = " << pthread_self() << ",number = " << number << endl;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void* funcB_num(void* arg) {
for (int i = 0; i < MAX; ++i) {
//访问全局变量前加锁
pthread_mutex_lock(&mutex);
int cur = number;
cur++;
number = cur;
cout << "Thread B,id = " << pthread_self() << ",number = " << number << endl;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(int argc,const char* argv[])
{
pthread_t pthA, pthB;
//互斥锁初始化
pthread_mutex_init(&mutex, NULL);
pthread_create(&pthA, NULL, funcA_num, NULL);
pthread_create(&pthB, NULL, funcB_num, NULL);
pthread_join(pthA, NULL);
pthread_join(pthB, NULL);
//释放互斥锁资源
pthread_mutex_destroy(&mutex);
return 0;
}
原子操作
cpu处理一个指令,线程/进程在处理完这个指令之前是不会失去cpu的