简体   繁体   中英

C: thread_mutex Sync

I am having a problem with multiple thread synchronization, I will post only an example of what I am doing to "try" the synchronization because the original code is larger. Basically I have a heavy process with 3 threads attached, to lock/unlock the threads I use functions that modifies the mutex state in each thread. Something like this:

## thread.c ##
    #include "thread.h"

extern int socks;

pthread_mutex_t sem = PTHREAD_MUTEX_INITIALIZER;

void lock()
{
    pthread_mutex_lock(&sem);
}

void unlock()
{
    pthread_mutex_unlock(&sem);
}

void* thread(void* arg)
{
    printf("Socks: %d\n",socks);
    lock();
    lock();

    printf("Unlocked\n");
    return;
}


## main.c ##
#include "defines.h"
#include "thread.h"

int socks;

int main()
{
    pthread_t tid;
    socks= 9;

    pthread_create(&tid, NULL, thread, NULL);

    //sleep(2);
    unlock();
    pthread_join(tid,NULL);
}

What I get after execute the code is:

./test

Socks: 9

Clearly I have some concepts wrong, but I can't find the problem. The thread shouldn't be unlocked with unlock()? Why the program works when I use sleep(2) before the unlock call? Which way should I use for avoid problems? Each code are in separated files.

Thanks in advance! PS: sorry for my crappy English!

Since the thread runs asynchronously, it might happen that the main thread joins before the thread has hit the lock. In this case I would suspect that the unlock() just happens too early, and the behaviour you get isn't well defined. If you let the main thread sleep for a while before you unlock, the other thread seems to have time to hit the lock and can be unlocked, resulting in the behaviour you seem to expect.

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