Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support SCOPE_EXIT macro #2643

Merged
merged 2 commits into from
May 19, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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]() {
BAIDU_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 BAIDU_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 BAIDU_SCOPE_EXIT \
chenBright marked this conversation as resolved.
Show resolved Hide resolved
auto BAIDU_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;
{
BAIDU_SCOPE_EXIT {
flag = true;
};
}
ASSERT_TRUE(flag);

{
BAIDU_SCOPE_EXIT {
flag = true;
};

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

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