Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include "domaci1.h"
- #define UNLOCKED 0
- #define WAITING 1
- #define TIMED_OUT 2
- typedef struct
- {
- int flag;
- struct node* next;
- int id;
- }node;
- node* tail;
- double minDelta = 1;
- int lock_n_threads_with_timeout(int id, int* local, int timeout)
- {
- double start = get_time();
- double dTimeout = (double)timeout/1000;
- int startInt = (int) start;
- node* novi = malloc(sizeof(node));
- novi->id=id;
- novi->flag=WAITING;
- novi->next=NULL;
- node* stari=(node*) get_and_set(&tail,novi);
- local[0]=novi;
- if(stari!=NULL)
- {
- stari->next=novi;
- while(1)
- {
- sleep(2);
- double end = get_time();
- int endInt = (int) end;
- double threadTime = end-start;
- if(threadTime<minDelta)
- {
- minDelta=threadTime;
- }
- if(threadTime>dTimeout)
- {
- if(novi->next==NULL)
- {
- if(!compare_and_set(&tail,novi,stari))
- {
- while(novi->next==NULL)
- {
- sleep(0);
- }
- compare_and_set(&novi->flag,WAITING,TIMED_OUT);
- }
- }
- else
- {
- while(1)
- {
- if(!compare_and_set(&novi->flag,WAITING,UNLOCKED))
- {
- node* temp=novi;
- novi=novi->next;
- free(temp);
- }
- else
- {
- break;
- }
- }
- }
- return 0;
- }
- if(novi->flag==0)
- {
- break;
- }
- }
- }
- return 1;
- }
- void unlock_n_threads_with_timeout(int id, int* local)
- {
- node* moj=local[0];
- if(moj->next!=NULL)
- {
- node* novi=moj->next;
- while(1)
- {
- if(!compare_and_set(&novi->flag,WAITING,UNLOCKED))
- {
- node* temp=novi;
- novi=novi->next;
- free(temp);
- }
- else
- {
- break;
- }
- }
- }
- else
- {
- if(!compare_and_set(&tail, moj,NULL))
- {
- while(moj->next==NULL)
- {
- sleep(0);
- }
- node *novi=moj->next;
- compare_and_set(&novi->flag,WAITING,UNLOCKED);
- }
- free(moj);
- }
- }
- int main()
- {
- tail=NULL;
- start_timeout_mutex_n_threads_test();
- printf("MinDelta: %lf",minDelta);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement