问题
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
回答1:
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.
回答2:
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...);
来源:https://stackoverflow.com/questions/13203307/variable-number-of-threads-c