question about using of malloc / free in pthreads

Victor vlyamtsev at mzeal.com
Thu Sep 4 13:38:52 UTC 2008


Hello,
I am working on some code where I have to pass data from couple of
"producer" threads to consumer.
I use "shared queue" approach, e.g. STL queue protected by mutex for passing
my "messages" between threads.

struct Block {
char* msg;
int size;
};
std::queue<block> fifo;
pthread_mutex_t *lock;

//producer thread

void *producer (void *_p)
{
while(true) 
{
  Block* buff = malloc(sizeof(Block));
  char* msg = malloc(128);
  strncpy(msg, "my msg");
  buff->msg = msg;
  buff->size = 128;
  // get mutex lock
if (pthread_mutex_lock(lock) == 0)
   fifo.push(buff);
pthread_mutex_unlock(lock)
sleep(10);
 } //end of while
} //end of producer

//consumer thread

void *consumer (void *_p)
{

while(true) 
{
 if (pthread_mutex_lock(lock) == 0)
 {
  Block *buff = fifo.front();
//do something here with message
  printf("%s", buff->msg);
...
//remove ptr from  queue
  fifo.pop(); 
//free msg memory
 free(buff->msg);
 free(buff);
 pthread_mutex_unlock(lock)
} //end of if
 } //end of while
} //end of consumer

int main() {
    
   lock = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t));
   pthread_mutex_init (lock, NULL);

    
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    
    pthread_create (&con, &attr, consumer, NULL);
    pthread_create (&pro, &attr, producer, NULL);
    
    // cleanup here   
    printf("End of program\n");
}

Program runs for while, but eventually it "segfaults", when trying to free
used "message" memory in consumer.
I wonder if I am missing some race condition associated with "alloc /free
cycle" here... 
Does memory allocation also has to be synchronized? E.g. should I create
separate mutex for memory allocation:
 pthread_mutex_t* mem_guard;
//instead of malloc in "producer" call:
if (pthread_mutex_lock(mem_guard) == 0) {
  Block* buff = malloc(sizeof(Block));
  char* msg = malloc(128);
  pthread_mutex_unlock(mem_guard)
}

//instead of free in "consumer" call:
if (pthread_mutex_lock(mem_guard) == 0) {
   //free msg memory
  free(buff->msg);
  free(buff);
  pthread_mutex_unlock(mem_guard)
}

Are there better approaches for IPC between pthreads?
Thank you for your advise...

-V

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://sourcerytools.com/pipermail/c++-pthreads/attachments/20080904/090dad93/attachment.html>


More information about the c++-pthreads mailing list