#include #include #include #include #include #include typedef int dint; typedef pid_t WHICH; typedef struct _LOCK LOCK; struct _LOCK { uint num; WHICH tid; }; WHICH Which() { return gettid(); } void Pause() { pthread_yield(); } void LockSiData( LOCK *shared ) { WHICH tid = Which(); while ( shared->tid != tid ) { if ( !(shared->tid) ) shared->tid = tid; Pause(); } shared->num++; } dint FreeSiData( LOCK *shared ) { if ( shared->tid == Which() ) { shared->num--; if ( !(shared->num) ) shared->tid = (WHICH)0; return 0; } return EACCES; } static LOCK l; static volatile int var = 0; static void *thread(void *arg) { int i; while (1) { LockSiData(&l); i = var++; if (i != 0) { printf("var = %d, expected 0\n", i); exit(1); } clock_nanosleep(CLOCK_MONOTONIC, 0, &(struct timespec){.tv_sec = 0, .tv_nsec = 1}, 0); i = var--; if (i != 1) { printf("var = %d, expected 1\n", i); exit(1); } FreeSiData(&l); } return 0; } int main(void) { pthread_t pt; int i; for (i = 0; i < 2; i++) { if ((errno = pthread_create(&pt, 0, thread, 0)) != 0) { printf("pthread_create failed: %m\n"); return 1; } } pthread_exit(0); }