Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
N
npvp-exercises
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Requirements
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Locked files
Build
Pipelines
Jobs
Pipeline schedules
Test cases
Artifacts
Deploy
Releases
Package registry
Container registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Code review analytics
Issue analytics
Insights
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
prietzem04
npvp-exercises
Commits
d19e6d09
Commit
d19e6d09
authored
1 year ago
by
kadsendino
Browse files
Options
Downloads
Patches
Plain Diff
Aufgabe 3
parent
dd867a39
No related branches found
No related tags found
No related merge requests found
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
aufgabe04/aufgabe3.c
+64
-0
64 additions, 0 deletions
aufgabe04/aufgabe3.c
with
64 additions
and
0 deletions
aufgabe04/aufgabe3.c
0 → 100644
+
64
−
0
View file @
d19e6d09
// dining philosophers with unshared chopsticks
#include
<stdio.h>
#include
<stdlib.h>
#include
<pthread.h>
#include
<semaphore.h>
#include
<unistd.h>
#define NUM_THREADS 5
sem_t
chopsticks
[
NUM_THREADS
];
void
*
Philosopher
(
void
*
threadid
)
{
long
tid
;
tid
=
(
long
)
threadid
;
for
(
int
i
=
0
;
i
<
10
;
i
++
)
{
// thinking
sleep
(
0
.
5
);
//wait
sem_wait
(
&
chopsticks
[
tid
]);
sem_wait
(
&
chopsticks
[(
tid
+
1
)
%
NUM_THREADS
]);
printf
(
"%ld Dining..
\n
"
,
tid
);
sleep
(
0
.
5
);
printf
(
"%ld Finished..
\n
"
,
tid
);
sem_post
(
&
chopsticks
[
tid
]);
sem_post
(
&
chopsticks
[(
tid
+
1
)
%
NUM_THREADS
]);
}
}
int
main
(
void
)
{
pthread_t
threads
[
NUM_THREADS
];
int
rc
;
long
t
;
for
(
int
i
=
0
;
i
<
NUM_THREADS
;
i
++
){
sem_init
(
&
chopsticks
[
i
],
0
,
1
);
}
for
(
t
=
0
;
t
<
NUM_THREADS
;
t
++
)
{
printf
(
"In main: creating thread %ld
\n
"
,
t
);
rc
=
pthread_create
(
&
threads
[
t
],
NULL
,
Philosopher
,
(
void
*
)
t
);
if
(
rc
)
{
printf
(
"ERROR; return code from pthread_create () is %d
\n
"
,
rc
);
exit
(
-
1
);
}
}
for
(
t
=
0
;
t
<
NUM_THREADS
;
t
++
)
{
pthread_join
(
threads
[
t
],
NULL
);
}
for
(
int
i
=
0
;
i
<
NUM_THREADS
;
i
++
){
sem_destroy
(
&
chopsticks
[
i
]);
}
return
0
;
}
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment