Benedikt Bünz
Benedikt Bünz

Reputation: 646

deleting pthread_t*

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

Upvotes: 0

Views: 2495

Answers (3)

111111
111111

Reputation: 16148

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.

Upvotes: 4

PiotrNycz
PiotrNycz

Reputation: 24402

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

Upvotes: 4

arrowd
arrowd

Reputation: 34401

Use delete[] threadNumber; when deleting arrays.

Upvotes: 0

Related Questions