You are on page 1of 2

Counting #include #include #include #include

semaphore <pthread.h> <stdio.h> <stdlib.h> <semaphore.h>

#define N 10 sem_t t_1_sem; sem_t t_2_sem; void *thread(void *vargp); /* shared by both threads*/ struct { int count; } thread_count; int main() { pthread_t tid, tid1; thread_count.count = 0; sem_init(&t_1_sem, 0, 1); sem_init(&t_2_sem, 0, 1); printf("Hello from main thread! tid:%ld pid:%d\n", pthread_self(), getpid()) ; pthread_create(&tid, NULL, thread, NULL); pthread_create(&tid1, NULL, thread, NULL); pthread_join(tid, NULL); pthread_join(tid1, NULL); exit(0); } void *thread(void *vargp) { int i, tid; int val, val2; sem_getvalue(&t_1_sem, &val); sem_getvalue(&t_2_sem, &val2); printf("initial value::: %d : %d\n", val, val2); tid = thread_count.count; thread_count.count += 1; for(i = 0;i<N;i++){ printf("%d, %d\n", tid, i); fflush(stdout); //sleep(0.1); } // TODO // barrier sem_getvalue(&t_1_sem, &val); sem_getvalue(&t_2_sem, &val2); printf("second value::: %d : %d\n", val, val2); int sem_val; if(tid == 0){

// free other sem_getvalue(&t_1_sem, &sem_val); printf("posting to 2, waiting on 1 w/ %d count\n", sem_val); sem_post(&t_2_sem); // wait on this one sem_wait(&t_1_sem); printf("done waiting on 1\n"); } else if(tid == 1){ sem_getvalue(&t_2_sem, &sem_val); printf("posting to 1, waiting on 2 w/ %d count\n", sem_val); sem_post(&t_1_sem); sem_wait(&t_2_sem); printf("done waiting on 2\n"); } sem_getvalue(&t_1_sem, &val); sem_getvalue(&t_2_sem, &val2); printf("final value::: %d : %d\n", val, val2); return NULL; }

You might also like