Skip to content

Instantly share code, notes, and snippets.

@ra1u
Created May 14, 2015 19:35
Show Gist options
  • Save ra1u/989dea95da65566f69a2 to your computer and use it in GitHub Desktop.
Save ra1u/989dea95da65566f69a2 to your computer and use it in GitHub Desktop.
transactonal memory dining philosopers
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct { int food; } philosoper_type;
static inline int eat(philosoper_type *philo, int *lfork, int *rfork) {
int r = 0;
while (!r) {
__transaction_atomic {
if (!(*lfork) && !(*rfork)) {
*lfork = *rfork = 1;
philo->food++;
r = 1;
*lfork = *rfork = 0;
}
}
}
return r;
}
typedef struct {
int *lfork;
int *rfork;
philosoper_type philo;
int food_to_eat;
} thread_msg_type;
void *eat_philo_eat(void *msg) {
thread_msg_type *m = (thread_msg_type *)msg;
for (int i=0;i < m->food_to_eat;++i) {
eat( &m->philo, m->lfork, m->rfork);
}
return NULL;
}
int main() {
const int N = 5;
const int food = 1000000;
pthread_t threads[N];
int forks[N];
thread_msg_type msg[N];
for (int i = 0; i < N; ++i) {
forks[i] = 0;
msg[i].lfork = &forks[i];
msg[i].rfork = &forks[(i+1)%N];
msg[i].food_to_eat = food;
int r = pthread_create(&threads[i], NULL, eat_philo_eat, &msg[i]);
assert(r == 0);
}
for (int i = 0; i < N; ++i) {
int r = pthread_join(threads[i], NULL);
assert(r == 0);
}
printf("done\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment