1
\$\begingroup\$

I have implemented a WaitGroup class to simulate WaitGroup in Go lang. Then I've found that I can use Barrier in a different manner, to achieve the same thing. My WaitGroup has some additional functionality, but in most scenarios Barrier just would do.

Question: Do you spot any design flaws in this style of using Barrier?

Code:

I have an instance of Barrier:

static Barrier WaitGroupBarrier = new Barrier(0);

Then I define my tasks (or threads) this way in multiple places - so I have not the actual number of tasks/threads:

for (int i = 0; i < 1000; i++) // in multiple places
{
 var t = new Task(() =>
 {
 try
 {
 WaitGroupBarrier.AddParticipant();
 // body
 }
 finally
 {
 WaitGroupBarrier.RemoveParticipant();
 }
 });
 t.Start();
}

And I wait for them to complete, this way:

if (WaitGroupBarrier.ParticipantsRemaining > 0)
{
 Console.WriteLine("waiting...");
 WaitGroupBarrier.SignalAndWait();
}
asked Jun 11, 2013 at 9:27
\$\endgroup\$
7
  • \$\begingroup\$ The question is about C#; not Go. I am "simulating" this feature of Go, in C#. It's not a comparison. BTW I like Go. \$\endgroup\$ Commented Jun 11, 2013 at 9:30
  • \$\begingroup\$ @svick How can I move this question there? Should I repeat it there or somebody would migrate it? Please guide me. \$\endgroup\$ Commented Jun 11, 2013 at 14:28
  • \$\begingroup\$ Probably the fastest way for you is to ask the question there again and then delete it here. Another option would be to flag it and ask for it to be moved. \$\endgroup\$ Commented Jun 11, 2013 at 15:38
  • \$\begingroup\$ OP, if you do this, let a link here in comment so that we can follow the question. \$\endgroup\$ Commented Jun 11, 2013 at 15:52
  • \$\begingroup\$ Yes, I'd like to see the answer to this... My C# skills are a few (read many) years old, and I'd like to see the solution! \$\endgroup\$ Commented Jun 12, 2013 at 10:49

1 Answer 1

3
\$\begingroup\$
if (WaitGroupBarrier.ParticipantsRemaining > 0) {
 WaitGroupBarrier.SignalAndWait();
}

The above is a non-atomic operation. Thus if the if branch gets evaluated and there is one remaining, but finishes before SignalAndWait, then this will throw an exception.

answered Jul 31, 2013 at 20:45
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.