Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define UNLOCKED 0
- #define LOCKED 1
- #define TIMED_OUT 2
- typedef struct Node{
- int flag;
- struct Node * next;
- } Node;
- Node* tail = NULL;
- int sucsses = NULL;
- double startID[80];
- double minTime = 10.0;
- double maxTime = 0.0;
- void init_MCSLock(){
- }
- int lock_n_threads_with_timeout(int id, int* local, int timeout)
- {
- double start = get_time();
- startID[id] = start;
- double wait = timeout/1000.0;
- Node* node = (Node*) malloc(sizeof(Node));
- node->flag = UNLOCKED;
- node->next = NULL;
- *local = node;
- Node* old = (Node*) get_and_set((int*)&tail, (int)node);
- if(old != NULL){
- node->flag = LOCKED;
- old->next = node;
- while (node->flag == LOCKED) {
- // printf("sleep1");
- // fflush(stdout);
- double end = get_time();
- double waitedTime = end - start;
- if(waitedTime > wait){
- // printf("timedOut ");
- // fflush(stdout);
- node->flag = TIMED_OUT;
- return 0;
- }
- sleep(1);
- }
- node->flag = UNLOCKED;
- }
- // node->flag = UNLOCKED; // da li trebamo odvde da otkljucavamo?
- return 1;
- }
- void unlock_n_threads_with_timeout(int id, int* local)
- {
- Node* node = (Node*) *local;
- if(node->next == NULL){
- sucsses = (Node*) compare_and_set((int*)&tail, (int)node, (int)NULL);
- if(sucsses){
- printf("sucsses ");
- fflush(stdout);
- }
- else{
- while(node->next == NULL){
- printf("sleep2");
- fflush(stdout);
- sleep(1);
- }
- // node->next->flag = 0;
- }
- } else{
- Node* nextNode = (Node*) node->next;
- if(nextNode->flag == TIMED_OUT){
- if(!(compare_and_set(&tail, nextNode, NULL))){
- nextNode = nextNode->next;
- printf("WTF? %d\n", id);
- fflush(stdout);
- }
- }else if (nextNode->flag == LOCKED){
- printf("LOCKED->UNLOCKED \n");
- fflush(stdout);
- nextNode->flag = UNLOCKED;
- nextNode = NULL;
- //free(node);
- }
- }
- double finalTime = get_time() - startID[id];
- if(finalTime > maxTime) maxTime = finalTime;
- if(finalTime < minTime) minTime = finalTime;
- }
- int main()
- {
- start_timeout_mutex_n_threads_test();
- printf("MAX DELTA = %.5lf\n", maxTime);
- printf("MIN DELTA = %.5lf\n", minTime);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement