Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <pthread.h>
- typedef struct {
- unsigned long state;
- } apc_lock_t;
- int apc_lock_init(apc_lock_t* lock)
- {
- lock->state = 0;
- }
- int apc_lock_try(apc_lock_t* lock)
- {
- int failed = 1;
- asm volatile
- (
- "xchgl %0, 0(%1)" :
- "=r" (failed) : "r" (&lock->state),
- "0" (failed)
- );
- return failed;
- }
- int apc_lock_get(apc_lock_t* lock)
- {
- int failed = 1;
- do {
- failed = apc_lock_try(
- lock);
- usleep(0);
- } while (failed);
- return failed;
- }
- int apc_lock_release(apc_lock_t* lock)
- {
- int released = 0;
- asm volatile (
- "xchg %0, 0(%1)" : "=r" (released) : "r" (&lock->state),
- "0" (released)
- );
- return !released;
- }
- void* pthread_test(void *input) {
- apc_lock_t* lock = (apc_lock_t*) input;
- if (lock) {
- int runs = 0;
- while (runs++ < 10) {
- printf("%lu (%d) get lock: %d\n", pthread_self(), runs, apc_lock_get(lock));
- printf("%lu has lock ...\n", pthread_self());
- sleep(1);
- printf("%lu (%d) release lock: %d\n", pthread_self(), runs, apc_lock_release(lock));
- fflush(stdout);
- }
- }
- pthread_exit(NULL);
- }
- int main(char **argv) {
- apc_lock_t lock;
- apc_lock_init(&lock);
- pthread_t threads[8];
- int next = 0;
- while (next < 8) {
- pthread_create(
- &threads[next], NULL,
- pthread_test, (void*) &lock
- );
- next++;
- }
- while (next--) {
- pthread_join(
- threads[next], NULL);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement