Take the 2-minute tour ×

I was messing with pthreads and I am facing a strange issue. I wrote a program that theoretically cannot end because it should enter a deadlock. Here it is:

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

unsigned int d = 0;
pthread_mutex_t d_lock;

void* add(void *threadid)
        d += 5;
        printf("d's value is %d\n", d);

int main (int argc, char **argv)
    pthread_t mythread;
    pthread_create(&mythread, NULL, add, NULL);

I have no idea why it doesn't halt and keeps printing ... Thanks.

EDIT: It seems that the mutex needs to be initialized in order for it to work. One of the ways to do this is to replace pthread_mutex_t d_lock; with pthread_mutex_t d_lock = PTHREAD_MUTEX_INITIALIZER; (statically initalize it) and the deadlock now happens. I did not see such a thing in the tutorial though.

share|improve this question
mutex can be recursive stackoverflow.com/questions/187761/… –  mathematician1975 Oct 22 '12 at 13:13
So... what's your question? It seems like you have it bahaving like it should! –  Celada Oct 22 '12 at 13:29
considering base-value initialization is covered in the POSIX.1c standard, if it is not in your tutorial you may wish to get an additional or alternative reference to use in addition. If they missed that they likely missed something else. –  WhozCraig Oct 22 '12 at 14:35
So you found the answer yourself. Good! Please remove the answer from the question and make it an answer. Answer the question yourself, that's ok. Then accept it after 2 hours. And give the link to Creating and Destroying Mutexes section. –  Jarekczek Oct 23 '12 at 7:00
add comment


Your Answer



Browse other questions tagged or ask your own question.