~~~~ 前面我写了关于条件变量的一篇博客,我就提到了,std里面没有信号量,当然linux下是有的,windows下也有,只是std里面找不到,然后去网上找,就发现是因为信号量可以直接用锁加条件变量实现它的功能,而且更加安全,我就想可以试一下,然后就写了一个信号量的类,外加例子。
先是实现:
#include <mutex>
#include <condition_variable>
typedef class semaplore{
public:
semaplore(){
count = 0;
}
inline void signal(){
std::unique_lock<std::mutex> lock(m);
count++;
cond.notify_one();
}
inline void wait(){
std::unique_lock<std::mutex> lock(m);
cond.wait(lock, [=](){return count > 0;});//这里使用的是仿函数
count--;
}
private:
std::mutex m;
std::condition_variable cond;
int count;
};
很简单很简单很简单,主要就是pv操作,signal和wait,下面是使用实例:
#include <mutex>
#include <condition_variable>
#include <thread>
#include <iostream>
#include <queue>
class semaplore{
public:
semaplore(){
count = 1;
}
~semaplore(){
}
inline void signal(){
std::unique_lock<std::mutex> lock(m);
count++;
cond.notify_one();
}
inline void wait(){
std::unique_lock<std::mutex> lock(m);
cond.wait(lock, [=](){return count > 0;});
count--;
}
private:
std::mutex m;
std::condition_variable cond;
int count;
};
semaplore sem;
std::deque<int> q;
void function_1() {
int count = 10;
while (count > 0) {
sem.wait();
q.push_front(count);
sem.signal();
std::this_thread::sleep_for(std::chrono::seconds(1));
count--;
}
}
void function_2() {
int data = 0;
while ( data != 1) {
sem.wait();
if(q.empty()){
sem.signal();
continue;
}
data = q.back();
q.pop_back();
sem.signal();
printf("function1 push_front a data to function2: %d \n", data);
}
}
int main() {
std::thread t1(function_1);
std::thread t2(function_2);
t1.join();
t2.join();
return 0;
}
下面是编译加结果
qilimi@qilimi-desktop:~/test$ vim semaplore.cpp
qilimi@qilimi-desktop:~/test$ g++ -o test5 semaplore.cpp -std=c++11 -lpthread
qilimi@qilimi-desktop:~/test$ ./test5
function1 push_front a data to function2: 10
function1 push_front a data to function2: 9
function1 push_front a data to function2: 8
function1 push_front a data to function2: 7
function1 push_front a data to function2: 6
function1 push_front a data to function2: 5
function1 push_front a data to function2: 4
function1 push_front a data to function2: 3
function1 push_front a data to function2: 2
function1 push_front a data to function2: 1
qilimi@qilimi-desktop:~/test$
就这样了,感觉好像好挫呀。
掀桌子了
(╯>д<)╯ ミ ┸┸)`ν゚) ┻━┻
摆好摆好
(#-_-)\┯━┯