Skip to content

Commit

Permalink
Use atomic sharedptr operation (for C++11~20) instead of reflock
Browse files Browse the repository at this point in the history
  • Loading branch information
Coldwings committed Jul 10, 2024
1 parent a8b6878 commit a78ebc2
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
12 changes: 6 additions & 6 deletions common/objectcachev2.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ class ObjectCacheV2 {
const K key;
std::shared_ptr<V> ref;
photon::spinlock boxlock;
photon::spinlock reflock;
uint64_t lastcreate = 0;
uint64_t timestamp = 0;

Expand All @@ -50,11 +49,12 @@ class ObjectCacheV2 {
// other reader will get new one after updated
std::shared_ptr<V> update(V* val, uint64_t ts = 0,
std::shared_ptr<V>* newptr = nullptr) {
SCOPED_LOCK(box->reflock);
auto r = std::shared_ptr<V>(val);
if (newptr) *newptr = r;
if (newptr)
std::atomic_store(newptr, r);
*newptr = r;
box->lastcreate = ts;
std::swap(r, box->ref);
r = std::atomic_exchange(&box->ref, r);
return r;
}

Expand All @@ -79,8 +79,7 @@ class ObjectCacheV2 {

Updater writer() { return Updater(this); }
std::shared_ptr<V> reader() {
SCOPED_LOCK(reflock);
return ref;
return std::atomic_load(&ref);
}
};
struct ItemHash {
Expand Down Expand Up @@ -173,6 +172,7 @@ class ObjectCacheV2 {
Borrow& operator=(Borrow&& rhs) {
std::swap(_oc, rhs._oc);
std::swap(_item, rhs._item);
_reader = std::atomic_exchange(&rhs._reader, _reader);
std::swap(_reader, rhs._reader);
std::swap(_recycle, rhs._recycle);
return *this;
Expand Down
4 changes: 2 additions & 2 deletions common/test/perf_objcache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ void *task(void *arg) {
for (const auto &x : k) {
auto strx = std::to_string(x);
auto b = oc->borrow(strx, [&strx] {
photon::thread_usleep(1 * 1000);
// photon::thread_usleep(1 * 1000);
// LOG_INFO("CTOR `", photon::now);
return new std::string(strx);
});
Expand All @@ -64,7 +64,7 @@ void test_objcache(OC<std::string, std::string *> &oc, const char *name) {

template <template <class, class> class OC>
void test(const char *name) {
OC<std::string, std::string *> oc(-1UL);
OC<std::string, std::string *> oc(0);
std::vector<std::thread> ths;
photon::semaphore sem(0);
for (int i = 0; i < 10; i++) {
Expand Down

0 comments on commit a78ebc2

Please sign in to comment.