[c++-pthreads] question about using of malloc / free in pthreads
kostya.kurilov
krizka at gmail.com
Thu Sep 4 17:26:30 UTC 2008
In spite of many errors and glitches in this code, the main problem
there is synchronization. You don't even check existance of the
element in queue, so you have to check it before get pointer by
calling queue.front() in consumer, the condition variables would be
the one of the best thing you can use here.
PS. Sorry for english and.. I think it's offtopic for this mailing list :)
On Thu, Sep 4, 2008 at 5:38 PM, Victor <vlyamtsev at mzeal.com> wrote:
> 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
--
Best regards, kostya.kurilov
More information about the c++-pthreads
mailing list