0
votes

I wrote a small pthread multithreadding programming and i wanted to clean up the pthred_t array which i created. But when I do it I get the error that a glib has been detected. How can I delete the array, or do I simply not need to. The code runs fine without the freeing of the memory but in my opinion the code below causes a (small) memory leek. Thanks

pthread_t* threadNumber = new pthread_t (4);
args var;
var.matrixA=matrixA;
var.matrixB=matrixB;
var.matrixC=matrixC;
var.alpha=alpha;
var.beta=beta;
var.cellCount=0;
var.maxCells=cColumns*cRows;

for (int i =0 ;i<4;++i)
  pthread_create(&threadNumber[i],&attr,matrixMultiply,(void *) (&var));

for(int i=0;i<4;++i)
  pthread_join(threadNumber[i],NULL);

printMatrix(matrixA,aRows,aColumns);
printMatrix(matrixB,bRows,bColumns);
printMatrix(matrixC,cRows,cColumns);

//delete threadNumber;
//this caused a memory trash
3
"I get the error that a glib has been detected" - made my day. - user529758
std::vector<pthread_t> threadNumber(4); <- brought to you by SLACK, the Standard Library Awareness Campaign Kids. - R. Martinho Fernandes
to add to Martinho comment, std::vector<std::thread> threads(4); - 111111

3 Answers

4
votes

You need square bracket to create array:

Not this:

pthread_t* threadNumber = new pthread_t (4);
//                                      ^ ^

But this is correct:

pthread_t* threadNumber = new pthread_t [4];
//                                      ^ ^

Your version is one pthread_t variable initialized to 4 - whatever this 4 means in this context - since pthread_t is opaque type.

So, with your wrong version you should delete with delete threadNumber, correct version delete with delete [] threadNumber

4
votes

I know you have answers for pthreads, however I think it might be of interest to you to consider the following.

 std::vector<std::thread> threads;

 for(int i=0; i!=4; ++i) threads.emplace_back(&my_function, args);

 for(auto& th : threads) th.join();

No need for manual clean up, and portable across any compliant compiler, unlike pthread which will only work across POSIX platforms.

However you might want to also look at libraries like Intel TBB if you are trying to split a single problem across many threads.

references

http://en.cppreference.com/w/cpp/thread/thread

http://en.cppreference.com/w/cpp/container/vector

N.b: if your compiler doesn't support C++11 (which it probably does) then boost has boost::thread which has a very similar interface and functionality.

0
votes

Use delete[] threadNumber; when deleting arrays.