Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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]() {
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