0

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!

Community
  • 1
  • 1
guille8
  • 45
  • 4
  • I see two `lock()` commands and neither appear to be protecting the `socks` variable. – sarnold Jun 29 '12 at 01:32
  • Why are there two consecutive `lock` call? It seems that one of your threads will block on the second `lock` and all other threads will block on the first `lock`. – Jinghao Shi Jun 29 '12 at 03:41
  • That is because the mutex starts open. So two locks are required to block the thread, I think. – guille8 Jun 29 '12 at 16:50
  • The int variable won't be modified, and the thread creation is after the assign. It is necessary to mutex that variable? – guille8 Jun 29 '12 at 16:53

1 Answers1

0

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.

blutfink
  • 402
  • 5
  • 9
  • I see. But the mutex state shouldn't be increased by unlock() even before lock? In that case, the lock won't block the thread. – guille8 Jun 29 '12 at 16:58
  • The mutex is initially unlocked. The spec for pthread_mutex_unlock() says: "Attempting to unlock the mutex if it was not locked by the calling thread results in undefined behavior." So the unlock() might just have no effect. – blutfink Jun 30 '12 at 00:21
  • Thank you blutfink! That was the problem, I replaced the pthread_mutex with POSIX semaphores and now it works flawlessly. – guille8 Jul 02 '12 at 20:09