I'm inclined towards using vectors and smart pointers instead of arrays as it is safer. The problem is that when initialised as an array, my threads join the main thread successfully. However, this is not the case when initialised as a vector. This is expected as the array elements are accessed by reference.
1. As array
pthread_t threads[numCPU]; // Initialised as an array
// Creating threads
for(long unsigned int i=0; i<numCPU; i++){
rc = pthread_create(&threads[i], &attr, myfunc, (void *) args[i] );
if (rc) {
printUserMessage(std::string("Error; return code from pthread_create is : ") + std::to_string(rc));
} else {
printUserMessage(std::string("Created Thread " + std::to_string(i)));
}
}
// Joining thread
for(long unsigned int i=0; i<numCPU;i++){
rc = pthread_join(threads[i], NULL);
if (rc) {
printUserMessage(std::string("Error; return code from pthread_create is : ") + std::to_string(rc));
} else {
printUserMessage(std::string("Joined Thread " + std::to_string(i)));
}
The signatures of pthread_create and pthread_join would be respected when:
std::vector<pthread_t *> threads(numCPU);
A vector of pointers doesn't make sense and I may have to manage memory. Is there a safer way to create threads?