Skip to content

Commit

Permalink
Removed time_t where ever possible and replaced it with std::chrono
Browse files Browse the repository at this point in the history
  • Loading branch information
COM8 committed Aug 17, 2024
1 parent ee96495 commit 42d2804
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 10 deletions.
9 changes: 5 additions & 4 deletions cpr/threadpool.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -132,14 +132,15 @@ void ThreadPool::AddThread(std::thread* thread) {
data.thread = std::shared_ptr<std::thread>(thread);
data.id = thread->get_id();
data.status = RUNNING;
data.start_time = time(nullptr);
data.stop_time = 0;
data.start_time = std::chrono::steady_clock::now();
data.stop_time = std::chrono::steady_clock::time_point::max();
threads.emplace_back(data);
thread_mutex.unlock();
}

void ThreadPool::DelThread(std::thread::id id) {
const time_t now = time(nullptr);
const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();

thread_mutex.lock();
--cur_thread_num;
--idle_thread_num;
Expand All @@ -153,7 +154,7 @@ void ThreadPool::DelThread(std::thread::id id) {
}
} else if (iter->id == id) {
iter->status = STOP;
iter->stop_time = time(nullptr);
iter->stop_time = std::chrono::steady_clock::now();
}
++iter;
}
Expand Down
4 changes: 2 additions & 2 deletions include/cpr/threadpool.h
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,8 @@ class ThreadPool {
std::shared_ptr<std::thread> thread;
std::thread::id id;
Status status;
time_t start_time;
time_t stop_time;
std::chrono::steady_clock::time_point start_time;
std::chrono::steady_clock::time_point stop_time;
};

std::atomic<Status> status{Status::STOP};
Expand Down
18 changes: 14 additions & 4 deletions test/post_tests.cpp
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
#include <chrono>
#include <cstddef>
#include <gtest/gtest.h>

#include <array>
#include <cstdio>
#include <fstream>
#include <string>

#include "cpr/cookies.h"
#include "cpr/cpr.h"
#include "cpr/multipart.h"

Expand Down Expand Up @@ -630,10 +633,17 @@ TEST(UrlEncodedPostTests, PostWithNoBodyTest) {
}

static std::string getTimestamp() {
char buf[1000];
time_t now = time(0);
struct tm* tm = gmtime(&now);
strftime(buf, sizeof buf, "%a, %d %b %Y %H:%M:%S GMT", tm);
const std::chrono::system_clock::time_point tp = std::chrono::system_clock::now();
const time_t timeT = std::chrono::system_clock::to_time_t(tp);
// NOLINTNEXTLINE(concurrency-mt-unsafe)
struct tm* tm = gmtime(&timeT);

std::string buf;
buf.resize(EXPIRES_STRING_SIZE);

const size_t s = strftime(buf.data(), buf.size(), "%a, %d %b %Y %H:%M:%S GMT", tm);
EXPECT_GT(s, 0);
buf.resize(s);
return buf;
}

Expand Down

0 comments on commit 42d2804

Please sign in to comment.