
Původně odeslal
THX
ok, to ifdef a ifndef som vsetko pokladal za ifndef
- problem je iny - citas zamknute data
ok. tak sec, opravim to ...
Kód:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
int a = 0;
int b = 0;
pthread_mutex_t mut_a = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mut_b = PTHREAD_MUTEX_INITIALIZER;
void *f_thread1 ();
void *f_thread2 ();
int
main (void)
{
pthread_t thread1, thread2;
int iret1, iret2;
iret1 = pthread_create (&thread1, NULL, f_thread1, NULL);
iret2 = pthread_create (&thread2, NULL, f_thread2, NULL);
pthread_join (thread1, NULL);
pthread_join (thread2, NULL);
printf ("a = %d\n", a);
printf ("b = %d\n", b);
exit (0);
}
void *
f_thread1 ()
{
int x = 0;
for (x = 0; x < 65535; x++)
{
int temp1, temp2;
{
#ifdef WHOLELOCK
pthread_mutex_lock (&mut_a);
pthread_mutex_lock (&mut_b);
#endif
#ifndef WHOLELOCK
pthread_mutex_lock (&mut_a);
#endif
temp1 = a + 1;
#ifndef WHOLELOCK
pthread_mutex_unlock (&mut_a);
pthread_mutex_lock (&mut_b);
#endif
temp2 = b + 1;
#ifndef WHOLELOCK
pthread_mutex_unlock (&mut_b);
pthread_mutex_lock (&mut_b);
#endif
b = temp2;
#ifndef WHOLELOCK
pthread_mutex_unlock (&mut_b);
pthread_mutex_lock (&mut_a);
#endif
a = temp1;
#ifndef WHOLELOCK
pthread_mutex_unlock (&mut_a);
#endif
#ifdef WHOLELOCK
pthread_mutex_unlock (&mut_a);
pthread_mutex_unlock (&mut_b);
#endif
}
}
}
void *
f_thread2 ()
{
int x = 0;
for (x = 0; x < 65535; x++)
{
int temp1, temp2;
{
#ifdef WHOLELOCK
pthread_mutex_lock (&mut_a);
pthread_mutex_lock (&mut_b);
#endif
#ifndef WHOLELOCK
pthread_mutex_lock (&mut_a);
#endif
temp1 = a - 1;
#ifndef WHOLELOCK
pthread_mutex_unlock (&mut_a);
pthread_mutex_lock (&mut_b);
#endif
temp2 = b - 1;
#ifndef WHOLELOCK
pthread_mutex_unlock (&mut_b);
pthread_mutex_lock (&mut_b);
#endif
b = temp2;
#ifndef WHOLELOCK
pthread_mutex_unlock (&mut_b);
pthread_mutex_lock (&mut_a);
#endif
a = temp1;
#ifndef WHOLELOCK
pthread_mutex_unlock (&mut_a);
#endif
#ifdef WHOLELOCK
pthread_mutex_unlock (&mut_a);
pthread_mutex_unlock (&mut_b);
#endif
}
}
}
Kód:
localhost ~ # gcc -pthread -o tt-nowholelock threadtest.c
localhost ~ # ./tt-nowholelock
a = 11691
b = -538
sice to neni presne to, co ma implementovany valve, protoze pri cteni zamykam jak pro cteni, tak pro zapis ... ale stejne ...