Hi to all, I have the following problem, I don't know if is possible to solve:
I have number of threads working, and I want that every thread to wait in some part of the code, until all the threads reach that part.
I'll explain may self:
1. In the Main thread create 'x' threads.
2. Every thread start working in its the method
3. When every thread reach some part of the code, he ask if all the other threads are in the same part
4. When all the threads reach that part, do some checking and continue

I know this is possible to wait for all threads when they finish their method, but I don't know if is possible to wait before their work. I know is possible to wait in the main thread for all the threads to end their work with "WaitHandle.WaitAll", but this method I can use it in main thread(meaning every thread go out of the its method/finsih its work).
I want something to check before the method goes out of its method.
Pseudo code:

Main
{
Create 10 Threads(CallBackThreadMethod) - Every thread start working
}
CallBackThreadMethod()
{
while(something)
{
DoWork();
Wait for all threads ->Wait for all the 9 threads to get here - Only when all the threads reach here
CheckSomething();
Continue working
}
}

Thanks

how about someting along the following sample. I had not time to test, but the idea is to create one Sync instance in the main thread and let the other theads call the WaitFor method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace util {
    class Sync {

        private int currentCount;
        private int requestedCount;

        public Sync(int nr) {
            this.requestedCount = nr;
        }

        public void WaitFor() {
            currentCount++;
            lock (this) {
                if (currentCount < requestedCount) {
                    System.Threading.Monitor.Wait(this);
                }
                System.Threading.Monitor.PulseAll(this);
            }
        }
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.