Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<pthread.h>
- #include<stdlib.h>
- #include<unistd.h>
- int var;
- pthread_mutext_t mutex;
- typedef struct s {
- int id;
- } s;
- void* t(void *inp) {
- s* inputs = (s*) inp;
- sleep(2);
- pthread_mutext_lock(&mutex);
- if (var == 0) {
- printf("Child %d didn't eat\n", inputs->id);
- else {
- printf("Child %d ate\n", inputs->id);
- var--;
- }
- pthread_mutext_unlock(&mutex);
- return NULL;
- }
- int main() {
- var = 1;
- printf("Total cookies: %d\n", var);
- pthread_t tid1;
- pthread_t tid2;
- s* thread1_input = (s*)malloc(sizeof(s));
- s* thread2_input = (s*)malloc(sizeof(s));
- thread1_input->id = 1;
- thread2_input->id = 2;
- pthread_mutext_init(&mutex, NULL);
- pthread_create(&tid1, NULL, t, (void*)(thread1_input));
- pthread_create(&tid2, NULL, t, (void*)(thread2_input));
- pthread_join(tid1, NULL);
- pthread_join(tid2, NULL);
- pthread_mutex_destroy(&mutex);
- printf("%d\n", var);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement