Skip to content

Instantly share code, notes, and snippets.

@mepcotterell
Last active August 17, 2019 14:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mepcotterell/9476eecf12ca424dcb91534a6fdf325c to your computer and use it in GitHub Desktop.
Save mepcotterell/9476eecf12ca424dcb91534a6fdf325c to your computer and use it in GitHub Desktop.
Critical Section Problem

Critical Section Problem

Use the following commands to compile and link the examples:

$ gcc -std=c17 -pedantic-errors -O0 -g -o problem problem.c -lpthread
$ gcc -std=c17 -pedantic-errors -O0 -g -o peterson0 peterson0.c -lpthread
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PING "ping"
#define PONG "pong"
void critical(const char * str) {
size_t len = strlen(str);
for (size_t i = 0; i < len; ++i) {
printf("%c", str[i]);
} // for
printf("\n");
} // str
int getid(const char * msg) {
if (strcmp(msg, PING) == 0) return 0;
if (strcmp(msg, PONG) == 0) return 1;
} // getid
volatile bool flag [2] = { false, false };
volatile int turn;
void * pingpong(void * p) {
char * msg = (char *) p;
int id = getid(msg);
for (;;) {
flag[id] = true;
turn = 1-id;
while (flag[1-id] && turn == (1-id));
critical(msg);
flag[id] = false;
} // for
} // pingpong
int main() {
setvbuf(stdout, NULL, _IONBF, 0);
pthread_t ping;
pthread_t pong;
pthread_create(&ping, NULL, pingpong, PING);
pthread_create(&pong, NULL, pingpong, PONG);
for(;;);
return 0;
} // main
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PING "ping"
#define PONG "pong"
void critical(const char * str) {
size_t len = strlen(str);
for (size_t i = 0; i < len; ++i) {
printf("%c", str[i]);
} // for
printf("\n");
} // critical
void * pingpong(void * p) {
char * msg = (char *) p;
for (;;) {
critical(msg);
} // for
} // pingpong
int main() {
setvbuf(stdout, NULL, _IONBF, 0);
pthread_t ping;
pthread_t pong;
pthread_create(&ping, NULL, pingpong, PING);
pthread_create(&pong, NULL, pingpong, PONG);
for(;;);
return 0;
} // main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment