Domanda

I have a program that have 3 threads.All of them take data from ethernet on different ports.The frequencies of the data coming for 3 of the threads may be different. But all of the incoming data must be processed at the same time.

So if one data comes for one thread, it must wait the others data to come. How can I get it?

È stato utile?

Soluzione

Boost.Thread has a barrier class, whose purpose is to block multiple threads until a specified number have reached the barrier.

You would just create a boost::barrier initialized with 3, meaning that it blocks until three threads are waiting on the barrier. When each of your threads is done waiting for data, you have them call wait() on the barrier. When the third thread calls wait(), all three threads will continue execution.

boost::barrier barrier(3);

void thread_function()
{
    read_data();
    barrier.wait(); // Threads will block here until all three are ready.
    process_data();
}

If you only want one thread to process the data, you can check the return value of wait(); the function will only return true for one of the threads at the barrier.

Altri suggerimenti

You need a barrier. Barrier has preset capacity N and blocks N-1 threads until N-th arrives. After the N-th arrives, all N threads are released simultaneously.

Unfortunately Qt has no direct support for barriers, but there is simple implementation using Qt primitives here: https://stackoverflow.com/a/9639624/1854587

Not as simple as boost's barrier as answered by @dauphic, but this can be done with Qt alone, using slots, signals and another class on a 4th thread.

Create a class on a separate thread that coordinates the other 3, the network threads can send a signal to the 'coordinator' class when they receive data. Once this coordinator class has received messages from all 3 network threads, it can then signal the threads to process the data.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top