1

In my program, I want to get number of threads from user. For example, user enters number of threads as 5, i want to create 5 threads. It is only needed in the beginning of the program. I don't need to change number of threads during the program. So, i write the code such as;

int numberOfThread;

cout << "Enter number of threads: " ;
cin >> numberOfThread;

for(int i = 0; i < numberOfThread; i++)
{
    pthread_t* mythread = new pthread_t;
    pthread_create(&mythread[i],NULL, myThreadFunction, NULL);
}

for(int i = 0; i < numberOfThread; i++)
{
    pthread_join(mythread[i], NULL);
}

return 0;

but i have an error in this line pthread_join(mythread[i], NULL);

error: ‘mythread’ was not declared in this scope.

What is wrong in this code? and do you have a better idea to create user defined number of thread?

NutCracker
  • 11,485
  • 4
  • 44
  • 68
  • 1
    You have a memory leak when creating threads. I suggest you using `std::thread` instead of `pthread_t` and not using pointers at all. – NutCracker Apr 07 '20 at 08:53
  • 1
    Your `mythread`-variable is local to your `for`-loop, it does not exist outside of it. – melk Apr 07 '20 at 09:03
  • 1
    You also have undefined behaviour: for any value of `i` > 0 `mythread[i]` is out of bounds. – G.M. Apr 07 '20 at 09:07

1 Answers1

2

First, you have a memory leak when creating threads because you allocate memory but then loose the reference to it.

I suggest you the following: create an std::vector of std::threads (so, don't use pthread_t at all) and then you can have something like:

std::vector<std::thread> threads;
for (std::size_t i = 0; i < numberOfThread; i++) {
    threads.emplace_back(myThreadFunction, 1);
}

for (auto& thread : threads) {
    thread.join();
}

if your myThreadFunction looks like:

void myThreadFunction(int n) {
    std::cout << n << std::endl; // output: 1, from several different threads
}
NutCracker
  • 11,485
  • 4
  • 44
  • 68