简体   繁体   中英

pthread_mutex_trylock and pthread_mutex_unlock cause segmentation fault

A mutex is required to be unlocked once the thread is canceled, in order to avoid deadlock. So I devised the following method:

// file_a.c
pthread_attr_t attr;
...
rc2 = pthread_attr_init(&attr);
ERR_IF( rc2 != 0 );
rc2 = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
ERR_IF( rc2 != 0 );
rc2 = pthread_create(&destroy_thread, &attr, destroy_expired_sessions, NULL);
ERR_IF( rc2 != 0 );
...
pthread_attr_destroy(&attr);

static void *destroy_expired_sessions(void *t)
{
    ...
    (void)t;

    pthread_cleanup_push(cleanup_handler, NULL);
    while (1)
    {
            ... // doing some work here

            sleep(min_timeout);
    }
    pthread_cleanup_pop(0);
}

static void cleanup_handler(void *arg)
{
    (void)arg;

    authSessionListMutexUnlock();
}

// file_b.c
typedef struct
{
    /** Mutex for using this structure. */
    pthread_mutex_t mutex;
    /** The list of Session nodes. */
    cList *list;
} SessionList;

SessionList *globalSessionList = NULL;

...

void authSessionListMutexUnlock()
{
    if (pthread_mutex_trylock(&globalSessionList->mutex) == EBUSY)
        pthread_mutex_unlock(&globalSessionList->mutex);
}

The reason I use pthread_mutex_trylock() here is to avoid a second pthread_mutex_unlock() if the mutex has been unlocked somewhere else.

However, the pthread_mutex_trylock() and pthread_mutex_lock() here caused a segmentation fault.

But, the program here seems innocuous, doesn't it?

You forgot to initialize your mutex using pthread_mutex_init() .

From experience, using an un-initialized mutex is a fairly safe bet to crash your program.

Another option is if you're attempting to unlock the mutex from another thread than you locked it from. The behavior of that operation is undefined.

Edit: A quick remark on the trylock/unlock; if the mutex is locked, you'll get EBUSY and unlock it, if the mutex is free, trylock will succeed in locking it and it won't be unlocked. In other words, it will toggle the lock/unlock status of the mutex. Is that really as you intended?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM