src.dualinventive.com/dinet/sec-multi-proxy/libdipp/tests/semaphore.cpp

77 lines
1.1 KiB
C++

#include <unistd.h>
#include <thread>
#include <iostream>
#include <functional>
#include <memory>
#include <di/Semaphore.h>
#include <gtest/gtest.h>
#include <atomic>
using namespace std;
using namespace Di;
static atomic_int callback_called(0);
static bool stop = false;
static Semaphore *sem;
void callback(void) {
for (int i = 0; i < 5 && !stop; i++) {
sem->wait();
callback_called++;
}
}
TEST(Semaphore, callFive) {
Semaphore s;
shared_ptr<thread> t;
sem = &s;
callback_called = 0;
t = make_shared<thread>(bind(callback));
usleep(100 * 1000);
sem->notify();
usleep(100 * 1000);
EXPECT_EQ(1, callback_called);
sem->notify();
usleep(100 * 1000);
EXPECT_EQ(2, callback_called);
sem->notify();
usleep(100 * 1000);
EXPECT_EQ(3, callback_called);
sem->notify();
usleep(100 * 1000);
EXPECT_EQ(4, callback_called);
sem->notify();
usleep(100 * 1000);
EXPECT_EQ(5, callback_called);
t->join();
t.reset();
}
TEST(Semaphore, notifyInAdvance) {
Semaphore s;
sem = &s;
sem->notify();
sem->notify();
sem->notify();
sem->notify();
sem->notify();
sem->wait();
sem->wait();
sem->wait();
sem->wait();
sem->wait();
}