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!