Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include "domaci1.h"
- #pragma clang diagnostic push
- #pragma ide diagnostic ignored "OCDFAInspection"
- typedef struct cvor {
- int flag;
- struct cvor *sledeci;
- int to;
- } cvor;
- cvor *tail = NULL;
- void unlock_flag(cvor *c) {
- if (!c->to) {
- cvor *sl = c->sledeci;
- if(sl==NULL) {
- if (lrk_compare_and_set((int *) &tail, (int) c, (int) NULL)) {
- free(c);
- } else {
- while (c->sledeci == NULL) {
- lrk_sleep(1);
- }
- printf("ovde");
- free(c);
- sl->flag=0;
- }
- }
- else {
- free(c);
- unlock_flag(sl);
- }
- }
- else {
- if (!lrk_compare_and_set(&(*c).flag, (c->to), 0)) {
- unlock_flag(c);
- }
- }
- }
- void unlock_n_threads_with_timeout(int id, int *local) {
- cvor *stari = (cvor *) local[0];
- if (stari->sledeci) {
- cvor *sl = stari->sledeci;
- free(stari);
- unlock_flag(sl);
- } else {
- if (lrk_compare_and_set((int *) &tail, (int) stari, (int) NULL)) {
- free(stari);
- } else {
- while (stari->sledeci == NULL) {
- lrk_sleep(1);
- }
- cvor *sl = stari->sledeci;
- free(stari);
- sl->flag = 0;
- }
- }
- }
- int lock_n_threads_with_timeout(int id, int *local, int timeout) {
- double time_started = lrk_get_time() * 1000;
- cvor *moj = (cvor *) malloc(sizeof(cvor));
- moj->sledeci = NULL;
- moj->flag = 1;
- moj->to = 1;
- cvor *stari = (cvor *) lrk_get_and_set((int *) &tail, (int) moj);
- local[0] = (int) moj;
- if (stari != NULL) {
- stari->sledeci = moj;
- while (moj->flag) {
- if (lrk_get_time() * 1000 - time_started > timeout) {
- moj->to = 0;
- if (moj->flag==0) {
- unlock_n_threads_with_timeout(id, local);
- /* if (moj->sledeci == NULL) {
- // if (compare_and_set((int *) &tail, (int) moj, (int) NULL)) {
- // free(moj);
- // } else {
- // while (moj->sledeci == NULL) {
- // lrk_sleep(1);
- // }
- // cvor *sl = moj->sledeci;
- // free(moj);
- // unlock_flag(sl);
- // }
- // } else {
- // unlock_flag(moj->sledeci);
- // free(moj);
- // } */
- }
- return 0;
- }
- lrk_sleep(1);
- }
- }
- // If timeout is too low
- // if (get_time() * 1000 - time_started > timeout) {
- // moj->to = 0;
- // if (moj->flag==0) {
- // unlock_n_threads_with_timeout(id, local);
- // }
- // return 0;
- // }
- return 1;
- }
- int main(int argc, char *argv[]) {
- int i = 200;
- if (argc==2) {
- i = atoi(argv[1]);
- }
- printf("Starting test with %d timeout:\n", i);
- // for (int i = 0; i < 10; ++i) {
- tail = NULL;
- start_timeout_mutex_n_threads_test(i);
- // }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement