This commit is contained in:
p-w-rs
2022-09-30 13:50:51 -05:00
parent 218bf07427
commit b927d70ba7
60 changed files with 793 additions and 433 deletions

View File

@@ -4,11 +4,11 @@
* Also does not work if a process does not want to access the critical section
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
// shared global
static int counter1 = 0;
@@ -20,7 +20,7 @@ volatile int start = 0;
// turn flag
volatile int turn = 0;
void* thread_routine(void* args)
void *thread_routine(void *args)
{
int me = *((int *)args);
int you = me ? 0 : 1;
@@ -28,11 +28,12 @@ void* thread_routine(void* args)
printf("Worker thread: %d ready, you are %d\n", me, you);
// wait for start from master thread
while(!start);
while (!start)
;
for (int j = 0; j < 1000; j++)
for (int j = 0; j < 100000; j++)
{
while(turn != me)
while (turn != me)
{
/* do nothing */
}
@@ -55,21 +56,23 @@ int main()
pthread_t thr1;
pthread_t thr2;
if(pthread_create(&thr1, NULL, thread_routine, (void*)&val1) == -1) {
if (pthread_create(&thr1, NULL, thread_routine, (void *)&val1) == -1)
{
printf("COULD NOT CREATE A THREAD\n");
exit(EXIT_FAILURE);
}
if(pthread_create(&thr2, NULL, thread_routine, (void*)&val2) == -1) {
if (pthread_create(&thr2, NULL, thread_routine, (void *)&val2) == -1)
{
printf("COULD NOT CREATE A THREAD\n");
exit(EXIT_FAILURE);
}
start = 1;
pthread_join(thr1,NULL);
pthread_join(thr2,NULL);
pthread_join(thr1, NULL);
pthread_join(thr2, NULL);
printf("counter1: %d\n",counter1);
printf("counter2: %d\n",counter2);
printf("counter1: %d\n", counter1);
printf("counter2: %d\n", counter2);
return EXIT_SUCCESS;
}