Dekker's algorithm

+1 Marin BeŇ°lo · December 19, 2015
Hello, I hope somebody can help me. I have to write a program:  mutual exclusion, where two threads mutual excluse each other by the algorithm of Dekker....

I wrote this:


#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

void *myfunc (void *myvar);

int main(int argc, char *argv[]){

pthread_t thread1, thread2;
char *mag1 = "First thread";
char *mag2 = "Second thread";


ret1 = pthread_create(&thread1, NULL, myfunc, (void *) mag1);
if(ret1 != 0){
printf("Error\n");
exit(1);
}
ret2 = pthread_create(&thread2, NULL, myfunc, (void *) mag2);
if(ret2 != 0){
printf("Error\n");
exit(1);
}

printf("Main function after pthread_create\n");


pthread_join(thread1, NULL);
pthread_join(thread2, NULL);

printf("First thread ret1 = %d\n", ret1);
printf("Second thread ret2 = %d\n", ret2);

return 0;
}

void *myfunc(void *myvar){
char *mag;
mag = (char *) myvar;

int i;
for(i=0; i < 5; i++){
printf("%s %d\n", mag, i);
sleep(1);
}
return NULL;
}

The output looks like:
First thread: 0
Sedond thread: 0
First thread: 1
Sedond thread: 1
First thread: 2
Sedond thread: 2
First thread: 3
Sedond thread: 3
First thread: 4
Sedond thread: 4


But i should by Dekkers algorithm excluse each other and the output should be like this:

First thread: 0
First thread: 1
First thread: 2
First thread: 3
First thread: 4
Sedond thread: 0
Sedond thread: 1
Sedond thread: 2
Sedond thread: 3
Sedond thread: 4

Hope somebody can help :)

Post a Reply

Replies

Oldest  Newest  Rating
0 Linguist Llama · December 23, 2015
Krootushas: Dekker's algorithm is basically an attempt at implementing mutex_lock and mutex_unlock.

Marin: What you need to realise is that implementing your own mutexes involves writing highly implementation-specific code, and you haven't told us anything about your implementation...

Nonetheless, as this forum is a good place to start for getting beginner help, your problem is probably too advanced for this forum. I suggest asking somewhere like StackOverflow, instead.
  • 1

C

124,556 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator