Reputation: 83
I want to learn thread usage and i don't know how to split for loop with treads.
For example:
vector x[100][100];
for ( int i = 0 ; i < 100 ; i++)
{
for ( int j = 0; j < 100 ; j++)
{
cout << x[i][j] << endl;
}
}
How to do this with 3 threads?
Upvotes: 0
Views: 2037
Reputation: 148900
You do not tell us enough.
When using multithreading for parallelizing tasks, you have 2 possible ways:
queue
) start the number of threads an let each take one value at a time with a mutex synchronizing the taking of valueFirst method is simpler to implement and will give correct results provided every processing has comparable load. Second method will still be optimal even if processing time can vary but will require thread synchronization.
Note that I did not give you a full implementation because aside from above generalities it will depend on real use case.
Upvotes: 0
Reputation: 11
If you care about the order of the output, that is if you want the elements printed in the same order as your simple nested loops print them, the answer is you can't, at least not efficiently. Doing things in order with threads requires synchronization, and that is expensive. Input and output are generally something you don't want multiple threads doing. You generally want at most one thread doing input and one doing output and if those need to be coordinated, only one thread doing both.
If you don't care about the order the elements are output, simply make the copies of the outer loop, the first copy doing 1 through 3, the second copy doing 4 to 6, and the last copy doing 7 to 10. Run each of rhe copies in its own thread.
Upvotes: 1