lock.h 2.38 KB
Newer Older
1
/*******************************************************************************
2
 * This file is part of SWIFT.
3
 * Copyright (c) 2012 Pedro Gonnet (pedro.gonnet@durham.ac.uk)
4
 *
5 6 7 8
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
9
 *
10 11 12 13
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
14
 *
15 16
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
 *
18
 ******************************************************************************/
19 20
#ifndef SWIFT_LOCK_H
#define SWIFT_LOCK_H
Pedro Gonnet's avatar
Pedro Gonnet committed
21

22 23 24 25
/* Some standard headers. */
#include <pthread.h>

/* Includes. */
26
#include "atomic.h"
27

28
#ifdef PTHREAD_SPINLOCK
29
#include <pthread.h>
30
#define swift_lock_type pthread_spinlock_t
31 32 33 34 35 36
#define lock_init(l) (pthread_spin_init(l, PTHREAD_PROCESS_PRIVATE) != 0)
#define lock_destroy(l) (pthread_spin_destroy(l) != 0)
#define lock_lock(l) (pthread_spin_lock(l) != 0)
#define lock_trylock(l) (pthread_spin_lock(l) != 0)
#define lock_unlock(l) (pthread_spin_unlock(l) != 0)
#define lock_unlock_blind(l) pthread_spin_unlock(l)
37
#define lock_static_initializer ((pthread_spinlock_t)0)
38

39
#elif defined(PTHREAD_LOCK)
40
#include <pthread.h>
41
#define swift_lock_type pthread_mutex_t
42 43 44 45 46 47
#define lock_init(l) (pthread_mutex_init(l, NULL) != 0)
#define lock_destroy(l) (pthread_mutex_destroy(l) != 0)
#define lock_lock(l) (pthread_mutex_lock(l) != 0)
#define lock_trylock(l) (pthread_mutex_trylock(l) != 0)
#define lock_unlock(l) (pthread_mutex_unlock(l) != 0)
#define lock_unlock_blind(l) pthread_mutex_unlock(l)
48
#define lock_static_initializer PTHREAD_MUTEX_INITIALIZER
49

Pedro Gonnet's avatar
Pedro Gonnet committed
50
#else
51
#define swift_lock_type volatile int
52 53 54
#define lock_init(l) (*(l) = 0)
#define lock_destroy(l) 0
INLINE static int lock_lock(volatile int *l) {
55
  while (atomic_cas(l, 0, 1) != 0)
56 57 58
    ;
  return 0;
}
59 60 61
#define lock_trylock(l) ((*(l)) ? 1 : atomic_cas(l, 0, 1))
#define lock_unlock(l) (atomic_cas(l, 1, 0) != 1)
#define lock_unlock_blind(l) atomic_cas(l, 1, 0)
62
#define lock_static_initializer 0
Pedro Gonnet's avatar
Pedro Gonnet committed
63
#endif
64 65

#endif /* SWIFT_LOCK_H */