0

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?

3
  • Doing this with three threads (or anything other than 1) is going to be a pointless waste of time. For your output to be meaningful, you need to keep it in order anyway. Commented Oct 24, 2015 at 18:19
  • You could delegate to your threads a row or column. So with 5 threads each thread could process 20 columns. You would decide how to divvy up the columns or rows. For example, the first thread could process columns 0 through 4 or columns 0, 5, 10, etc. Commented Oct 24, 2015 at 18:28
  • thank you for your answers. If order is not important, purpose is only showing all elements of vector,what should i do ? Again, could i delegate to my threads a row and column? Commented Oct 24, 2015 at 18:33

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You do not tell us enough.

When using multithreading for parallelizing tasks, you have 2 possible ways:

  • start each worker with a definite list of tasts (in your example first and second threads will get 33 values each and last 34)
  • put all values in a list (could be a queue) start the number of threads an let each take one value at a time with a mutex synchronizing the taking of value

First 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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.