文章内容
1. 信号量
为了使总进程和子线程两者之间可以有序的打印,对上一篇文章末尾的程序添加信号量
用同一个数p,主进程p从3开始递增5次,线程p从3开始递减10次
#include <pthread.h>
#include <unistd.h>
#include <iostream>
#include <semaphore.h>
using namespace std;
sem_t sem; // 全局变量
void* handle(void* p){
int* pn = (int*)p;
for(int i=0;i<10;++i){
sleep(1);
sem_wait(&sem); // 上锁
cout << pthread_self() << ":" << --*pn << endl;
sem_post(&sem); // 解锁
}
delete pn;
return NULL;
}
pair<pthread_t,int*> test(){
int* p = new int(3);
pthread_t tid;
pthread_create(&tid,NULL,handle,p);
return {
tid,p};
}
int main(){
sem_init(&sem,0,1); // 信号量创建
cout << getpid() << endl;
cout << pthread_self() << endl;
auto [tid,p] = test(); // c++17
int n = 5;
for(int i=0;i<5;++i){
sleep(1);
sem_wait(&sem); // 上锁
cout << pthread_self() << ":" << ++*p << endl;
sem_post(&sem); // 解锁
}
pthread_join(tid,NULL);
sem_destroy(&sem); // 信号量销毁
return 0;
}
结果为:
[root@foundation1 C++7.13]# g++ thread4.cpp -pthread -std=c++17
[root@foundation1 C++7.13]# ./a.out
11460
139913218471744
139913200518912:2
139913218471744:3
139913200518912:2
139913218471744:3
139913200518912:2
139913218471744:3
139913200518912:2
139913218471744:3
139913200518912:2
139913218471744:3
139913200518912:2
139913200518912:1
139913200518912:0
139913200518912:-1
139913200518912:-2
并发过程中在2和3僵持,等待阶段开始递减
2. 互斥量
分类:
分类 | 实现 | 特点 |
---|---|---|
静态分配互斥量 | pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER; | 简单 |
动态分配互斥量 | pthread_mutex_init(&mutex, NULL); pthread_mutex_destroy(&mutex); | 可以设置更多的选项 |
操作:
操作 | 函数 |
---|---|
加锁 | int pthread_mutex_lock(pthread_t *mutex) |
尝试加锁 | int pthread_mutex_trylock(pthread_t *mutex) |
解锁 | int pthread_mutex_unlock(pthread_t *mutex) |
示例:
使用静态分配互斥量 pthread_mutex_t 互斥锁
加锁 pthread_mutex_lock(&互斥锁)
解锁 pthread_mutex_unlock(&互斥锁)
使用动态分配互斥量 pthread_mutex_init(&互斥锁, NULL);
动态分配销毁 pthread_mutex_destroy(&互斥锁);
(也可以不加)
互斥量,也叫互斥锁,比信号量简单一些
把之前的所换成互拆锁
#include <pthread.h>
#include <unistd.h>
#include <iostream>
#include <semaphore.h>
using namespace std;
// sem_t sem;
pthread_mutex_t mutex; //