Michelle Dupuis
Michelle Dupuis

Reputation: 337

need to free a mutex?

I have a very simple (sample) C program as follows. I want to ensure I release any resources necessary so that valgrind does not complain. Do I need to free mutex1? Or do anything before the program terminates? Or is the mutex1 not allocate memory?

02  pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
03  int counter=0;
04   
05  /* Function C */
06  void functionC()
07  {
08     pthread_mutex_lock( &mutex1 );
09     counter++
10     pthread_mutex_unlock( &mutex1 );
11  }

Upvotes: 2

Views: 2844

Answers (3)

Tony Bai
Tony Bai

Reputation: 151

mutex1 in your code is a global variable rather than a heap-allocated variable. You do not need to free it. The OS will free all resources that your app use when you app terminate.

Upvotes: 0

Duck
Duck

Reputation: 27542

No, it is fine as it is. It is not necessary to use pthread_mutex_destroy on a statically allocated mutex.

Upvotes: 3

jweyrich
jweyrich

Reputation: 32240

No, you don't need to free mutex1. PTHREAD_MUTEX_INITIALIZER is a macro that hides a struct initialisation.

Upvotes: 3

Related Questions