Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/msg.h>
- #include <stdlib.h>
- #include <signal.h>
- #include <sys/shm.h>
- #include <time.h>
- #include <pthread.h>
- #define THREADS 2
- key_t key1; // zmienne na klucze
- int shmid;
- int *buffor= NULL;
- pthread_mutex_t m1,m2,m3,m4;
- pthread_t p_thread[THREADS];
- pid_t pid1, pid2;
- void sig_handler (int sig){
- pthread_mutex_unlock(&m1);
- pthread_mutex_unlock(&m2);
- pthread_mutex_unlock(&m3);
- pthread_mutex_unlock(&m4);
- pthread_mutex_destroy(&m1);
- pthread_mutex_destroy(&m2);
- pthread_mutex_destroy(&m3);
- pthread_mutex_destroy(&m4);
- kill(getpid(), SIGKILL);
- }
- void *watek2(void *arg) {
- int check=1;
- srand(time(0));
- while(check==1){
- usleep(rand()%200);
- pthread_mutex_lock(&m3);
- printf("Konsument K1 odczytal liczbe %d\n",*buffor);
- if(*buffor==100) check=0;
- pthread_mutex_unlock(&m1);
- }
- pthread_exit((void*)1);
- }
- void *watek1(void *arg){
- int check=1;
- srand(time(0));
- while(check==1){
- usleep(rand()%200);
- pthread_mutex_lock(&m4);
- printf("Konsument K2 odczytal liczbe %d\n",*buffor);
- if(*buffor==100) check=0;
- pthread_mutex_unlock(&m2);
- }
- pthread_exit((void*)1);
- }
- int main(void){
- if ((key1 = ftok(".", 'A')) == -1)
- errx(1, "Blad tworzenia klucza!");
- shmid = shmget(key1, sizeof(int), IPC_CREAT|0600);
- if (shmid == -1){
- perror("Utworzenie segmentu pamieci wspoldzielonej");
- exit(1);
- }
- buffor = shmat(shmid, NULL, 0);
- if (buffor == NULL){
- perror("Przylaczenie segmentu pamieci wspoldzielonej");
- exit(1);
- }
- if(pthread_mutex_init(&m1, NULL)!=0){
- printf("Blad przy tworzeniu mutex1! \n");
- exit(1);
- }
- if(pthread_mutex_init(&m2, NULL)!=0){
- printf("Blad przy tworzeniu mutex1! \n");
- exit(1);
- }
- if(pthread_mutex_init(&m3, NULL)!=0){
- printf("Blad przy tworzeniu mutex1! \n");
- exit(1);
- }
- if(pthread_mutex_init(&m4, NULL)!=0){
- printf("Blad przy tworzeniu mutex1! \n");
- exit(1);
- }
- pthread_mutex_lock(&m3);
- pthread_mutex_lock(&m4);
- int arg=1;
- if(pthread_create(&p_thread[0], NULL, watek1, (void *)arg)){
- printf("Blad przy tworzeniu watku1! \n");
- exit(1);
- }
- if(pthread_create(&p_thread[1], NULL, watek2, (void *)arg)){
- printf("Blad przy tworzeniu watku2! \n");
- exit(1);
- }
- int i=0;
- while(i<=100){
- signal(SIGINT, sig_handler);
- pthread_mutex_lock(&m1);
- pthread_mutex_lock(&m2);
- *buffor = i;
- printf("Producent zapisal liczbe %d\n",*buffor);
- pthread_mutex_unlock(&m3);
- pthread_mutex_unlock(&m4);
- i++;
- }
- pthread_join(p_thread[0], NULL);
- pthread_join(p_thread[1], NULL);
- sleep(5);
- kill(getpid(), SIGINT);
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement