-1

I need to create a c++ program that creates a number, a, of threads and then for each thread, n (0<n<a), asks each thread to sum numbers from 0 to n. So, for example, if the a=5, I need to create 5 threads and the third thread will need to add from 0 to 3. I use the main function and a while loop to dynamically create threads (using pthread_create, I have to use pthreads). Then I have one generic function that all the threads run. My problem is I don't know how to let each thread know which number is it. So, how would the third thread know that it is the third and not the first.

I'm sure this is simple, but I haven't been able to find the answer.

Thanks for your help!

etk1220

111111
  • 15,686
  • 6
  • 47
  • 62
etk1220
  • 197
  • 4
  • 9
  • If this is homework - please tag it as such. – Mike Dinescu Nov 02 '12 at 21:32
  • 4
    @MikyDinescu The homework tag is [offically deprecated](http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated) – Collin Nov 02 '12 at 21:33
  • not homework, i rephrased the problem so it would be simple to explain, I just need to find a way to make each thread know which number it is in a program with a dynamic number of threads thx – etk1220 Nov 02 '12 at 21:34
  • "I'm sure this is simple, but I haven't been able to find the answer." Because of course the homework is for you to go out and find a ready-made answer out there, right? You're not supposed to actually learn how to figure this out yourself. – bames53 Nov 02 '12 at 21:42

2 Answers2

2

Creating a variable amount of threads is not hard. For example:

void * func(void *);

std::vector<pthread_t> threads(n);

for (std::vector<pthread_t>::iterator it = threads.begin(); it != threads.end(); ++it)
{
    int r = pthread_create(&*it, NULL, func, args);
}

You'll need to add error checking and a suitable roll-back mechanic in case of errors. With the <thread> library it would be much simpler, but you said you can't use that.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

Well if you can use std::threads then this is trivail, you can just extend this to do your work

 std::vector<std::thead> threads;
 threads.push_back(&your_function, args...);
111111
  • 15,686
  • 6
  • 47
  • 62