Skip to content

Commit

Permalink
Merge pull request #2643 from chenBright/scope_exit
Browse files Browse the repository at this point in the history
Support SCOPE_EXIT macro
  • Loading branch information
yanglimingcn committed May 19, 2024
2 parents ff140be + 450deb4 commit b601c89
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/butil/endpoint.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -467,11 +467,11 @@ int pthread_timed_connect(int sockfd, const struct sockaddr* serv_addr,
butil::make_non_blocking(sockfd);
}
// Scoped non-blocking.
auto guard = butil::MakeScopeGuard([is_blocking, sockfd]() {
BRPC_SCOPE_EXIT {
if (is_blocking) {
butil::make_blocking(sockfd);
}
});
};

const int rc = ::connect(sockfd, serv_addr, addrlen);
if (rc == 0 || errno != EINPROGRESS) {
Expand Down
26 changes: 26 additions & 0 deletions src/butil/memory/scope_guard.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#define BRPC_SCOPED_GUARD_H

#include <type_traits>
#include "butil/macros.h"

namespace butil {

Expand Down Expand Up @@ -83,6 +84,31 @@ ScopeGuard<Callback> MakeScopeGuard(Callback&& callback) noexcept {
return ScopeGuard<Callback>{ std::forward<Callback>(callback)};
}

namespace internal {
// for BAIDU_SCOPE_EXIT.
enum class ScopeExitHelper {};

template<typename Callback>
ScopeGuard<Callback>
operator+(ScopeExitHelper, Callback&& callback) {
return MakeScopeGuard(std::forward<Callback>(callback));
}
} // namespace internal
} // namespace butil

#define BRPC_ANONYMOUS_VARIABLE(prefix) BAIDU_CONCAT(prefix, __COUNTER__)

// The code in the braces of BAIDU_SCOPE_EXIT always executes at the end of the scope.
// Variables used within BAIDU_SCOPE_EXIT are captured by reference.
// Example:
// int fd = open(...);
// BAIDU_SCOPE_EXIT {
// close(fd);
// };
// use fd ...
//
#define BRPC_SCOPE_EXIT \
auto BRPC_ANONYMOUS_VARIABLE(SCOPE_EXIT) = \
::butil::internal::ScopeExitHelper() + [&]() noexcept

#endif // BRPC_SCOPED_GUARD_H
19 changes: 19 additions & 0 deletions test/scope_guard_unittest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,25 @@ TEST(ScopedGuardTest, sanity) {
}
ASSERT_TRUE(flag);

flag = false;
{
BRPC_SCOPE_EXIT {
flag = true;
};
}
ASSERT_TRUE(flag);

{
BRPC_SCOPE_EXIT {
flag = true;
};

BRPC_SCOPE_EXIT {
flag = false;
};
}
ASSERT_TRUE(flag);

flag = false;
{
auto guard = butil::MakeScopeGuard([&flag] {
Expand Down

0 comments on commit b601c89

Please sign in to comment.