Skip to content

Commit d7d5100

Browse files
IronsDu杜钟伟claude
authored
Fix thread safety in WaitGroup and add static linkage to memsearch (#147)
- Add mutex locking to WaitGroup::add() and done() for thread safety - Only notify when counter reaches zero in done() - Return bool from timed wait() to indicate success - Change mCounter from atomic<int> to int (now protected by mutex) - Add static to memsearch in PromiseReceive for internal linkage Co-authored-by: 杜钟伟 <duzw@gdmbase.com> Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 22c761b commit d7d5100

2 files changed

Lines changed: 10 additions & 5 deletions

File tree

include/brynet/base/WaitGroup.hpp

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,18 @@ class WaitGroup : public NonCopyable
2525
public:
2626
void add(int i = 1)
2727
{
28+
std::unique_lock<std::mutex> l(mMutex);
2829
mCounter += i;
2930
}
3031

3132
void done()
3233
{
34+
std::unique_lock<std::mutex> l(mMutex);
3335
--mCounter;
34-
mCond.notify_all();
36+
if (mCounter <= 0)
37+
{
38+
mCond.notify_all();
39+
}
3540
}
3641

3742
void wait()
@@ -43,10 +48,10 @@ class WaitGroup : public NonCopyable
4348
}
4449

4550
template<class Rep, class Period>
46-
void wait(const std::chrono::duration<Rep, Period>& timeout)
51+
bool wait(const std::chrono::duration<Rep, Period>& timeout)
4752
{
4853
std::unique_lock<std::mutex> l(mMutex);
49-
mCond.wait_for(l, timeout, [&] {
54+
return mCond.wait_for(l, timeout, [&] {
5055
return mCounter <= 0;
5156
});
5257
}
@@ -61,7 +66,7 @@ class WaitGroup : public NonCopyable
6166

6267
private:
6368
std::mutex mMutex;
64-
std::atomic<int> mCounter;
69+
int mCounter;
6570
std::condition_variable mCond;
6671
};
6772
}}// namespace brynet::base

include/brynet/net/PromiseReceive.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
namespace brynet { namespace net {
66

77
/* binary search in memory */
8-
void memsearch(const char* hay, size_t haysize, const char* needle, size_t needlesize, size_t& result, bool& isOK)
8+
static void memsearch(const char* hay, size_t haysize, const char* needle, size_t needlesize, size_t& result, bool& isOK)
99
{
1010
size_t haypos, needlepos;
1111
haysize -= needlesize;

0 commit comments

Comments
 (0)