c++ - Program to create a number of threads based on user input not working (cin)? -
my apologies if question looks simple. i'm still learning threads. tried searching solution on here didn't find any.
i'm trying program create number of threads based on user input (ex: "cin >> 5" create 5 threads) says "i" in "threads mythreads[ ]" needs constant value. code below:
void exec(int n) { cout << "thread " << n << endl; } int main() { int numthreads = 0; // create threads cin >> numthreads; thread mythreads[numthreads]; // part says mythreads "must constant value" (int = 0; < numthreads; i++) { mythreads[i] = thread(exec, i); } (int = 0; < numthreads; i++) { mythreads[i].join(); } cout << "done!" << endl; }
any ideas how section can fixed? i've tried few different ways haven't worked far. thank much.
there's no problem multithreading. problem static array using dynamic array.
try this:
thread* mythreads = new thread[numthreads];
more dynamic memory in c++: http://www.cplusplus.com/doc/tutorial/dynamic/
upd james adkison: not forget delete[]
array avoid memory leaking.
Comments
Post a Comment