Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <pthread.h>
- #include <errno.h>
- #include <semaphore.h>
- pthread_mutex_t mtx;
- sem_t sem;
- int n = 5, count;
- typedef struct thread
- {
- pthread_t thr;
- int id;
- }thread;
- struct thread th[5];
- void barrier_point()
- {
- pthread_mutex_lock(&mtx);
- count++;
- pthread_mutex_unlock(&mtx);
- if(count < n)
- {
- sem_wait(&sem);
- }
- else
- {
- for(int i = 0; i < n; i++) sem_post(&sem);
- }
- }
- void* tfun(void* v)
- {
- int id = *(int*) v;
- printf("%d reached the barrier\n", id);
- barrier_point();
- printf("%d passed the barrier\n", id);
- return NULL;
- }
- int main()
- {
- if(pthread_mutex_init(&mtx,NULL))
- {
- perror(NULL);
- return errno;
- }
- if(sem_init(&sem, 0, 0))
- {
- perror(NULL);
- return errno;
- }
- for(int i = 0; i < n; i++)
- {
- th[i].id = i;
- pthread_create(&th[i].thr, NULL, tfun, &th[i].id);
- }
- for(int i = 0; i < n; i++) pthread_join(th[i].thr, NULL);
- pthread_mutex_destroy(&mtx);
- sem_destroy(&sem);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement