Pthread_mutex_trylock blocks when called simultaneously by two threads

I use pthread_mutex_trylockto lock the mutex in the structure so that it can be accessed or modified by only one thread at a time. If the mutex is already locked, I just return from the procedure, not the queue / lock.

This is the main outline of my code:

typedef struct {
    pthread_mutex_t m;
} myStruct;

void setupStruct(myStruct* struc) {
    pthread_mutex_init(&struc->m, NULL);
}

void structOp(myStruct* struc) {

    printf("structOp(): Trying to lock\n");

    if(pthread_mutex_trylock(&struc->m) != 0) {
        printf("structOp(): Lock failed\n");
        return;
    } else {
        printf("structOp(): Locked\n");
        // do some stuff to struct
        pthread_mutex_unlock(&struc->m);
    }
}

The structure is initialized as follows:

myStruct* struc = malloc(sizeof(struc));
setupStruct(struc);

However, sometimes when two threads invoke a procedure at the same time, both calls trylockdo not seem to be blocked. I guess this is because it prints “Attempt to block” for both threads at the same time, but does not print if the mutex is locked. For this reason, I had this problem with pthread_mutex_lock, so for this reason I tried the non-blocking version, but it is still blocked.

, first two . , .

, ? - - ? , .

+5
2

:

    myStruct* struc = malloc(sizeof(struc)); 

, , , / , . sizeof(struc) struc, struc - myStruct*, (, 4 8 )

    myStruct* struc = malloc(sizeof *struc); 

    myStruct* struc = malloc(sizeof(myStruct)); 
+8

- . , , .

valgrind, memcheck helgrind.

0

All Articles