novice pthread problem

From: Capstar (spam0_at_eg.homeip.net)
Date: 09/16/03


Date: Tue, 16 Sep 2003 16:25:30 +0200

I have the next code:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

struct buffer_t
{
   pthread_mutex_t lock;
   char *data;
};

struct global_t
{
   int buffer_cnt;
   struct buffer_t *buffers;
};

void *readbuffer(void* arg)
{
   struct global_t *g = (struct global_t *)arg;
   int i;

   for(i=0;i<g->buffer_cnt;++i)
   {
     pthread_mutex_lock(&g->buffers[i].lock);
     printf("%s\n", g->buffers[i].data);
     free(g->buffers[i].data);
     pthread_mutex_unlock(&g->buffers[i].lock);
   }

   pthread_exit(NULL);
}

int main(void)
{
   struct global_t g;
   pthread_t thread;
   int rc;

   g.buffer_cnt=1;
   g.buffers=malloc(sizeof*g.buffers);
   pthread_mutex_init(&g.buffers[0].lock, NULL);
   pthread_mutex_lock(&g.buffers[0].lock);
   rc=pthread_create(&thread, NULL, readbuffer, (void*)&g);
   if(rc)
   {
     printf("Unable to start readbuffer\n");
     return 1;
   }
   printf("Enter something: ");
   scanf("%as", &g.buffers[0].data);
   pthread_mutex_unlock(&g.buffers[0].lock);
   pthread_join(thread, NULL);
   pthread_mutex_destroy(&g.buffers[0].lock);
   free(g.buffers);
   printf("done\n");

   pthread_exit(0);
}

When I run this, it seems to work fine:
Enter something: test
test
done

But when I run it with valgrind I get the following output (partial output):

Enter something: test
test
done

sched status:

Thread 1: status = WaitJoiner, associated_mx = 0x0, associated_cv = 0x0
==1559== at 0x4024622D: thread_exit_wrapper (vg_libpthread.c:572)
==1559== by 0x40246490: pthread_detach (in
/usr/local/lib/valgrind/libpthread.so)
==1559== by 0x80488C4: main (in /home/marks/temp/ptest/ptest)
==1559== by 0x4028717D: __libc_start_main
(../sysdeps/generic/libc-start.c:129)
==1559== by 0x8048611: pthread_mutex_unlock@@GLIBC_2.0 (in
/home/marks/temp/ptest/ptest)

==1559==
==1559== Warning: pthread scheduler exited due to deadlock
==1559== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
==1559== malloc/free: in use at exit: 0 bytes in 0 blocks.
==1559== malloc/free: 5 allocs, 5 frees, 345 bytes allocated.
==1559==
==1559== No malloc'd blocks -- no leaks are possible.

Were is that deadlock supposed to occur and why? I don't see it. And I
also don't understand that according to the backtrace main is called by
__libc_start_main, which is called by pthread_mutex_unlock. Normally I
see all programs being start by __libc_start_main, which is the first in
the backtrace.

Thanks in advance,
   Mark



Relevant Pages