Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #include<unistd.h>
- #include<string.h>
- #include<pthread.h>
- #include<time.h>
- #define N 2
- /*
- Come usare signal e wait
- pthread_cond_broadcast(&cond); --> //sveglia tutti i threads che hanno chiamato wait su quella condizione
- pthread_cond_signal(&cond); --> //sveglia uno qualsiasi dei thread che dorme sulla condizione
- pthread_cond_wait(&cond, &mut); //mi addormento su quella condizione, fa unlock, al momento del risveglio è già in lock
- */
- int x, y;
- int addormentato = 0;
- pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
- pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
- int retcode = 999;
- void* incrementax(void* arg)
- {
- for(;;) {
- pthread_mutex_lock(&mutex);
- if (x > 200) {
- printf("x ha finito\n");
- pthread_mutex_unlock(&mutex);
- pthread_exit((void *) &retcode);
- }
- if (x > (y+10)) {
- printf("x %d > y %d\n", x, y);
- printf("thread tx: zZzZzZzZ\n");
- addormentato = 1;
- pthread_cond_wait(&cond,&mutex);
- addormentato = 0;
- printf("tx: svegliato con x=%d\n", x);
- pthread_mutex_unlock(&mutex);
- } else {
- x = x + 3;
- printf("thread tx: x = %d\n", x);
- pthread_mutex_unlock(&mutex);
- }
- usleep(20000L);
- }
- }
- void* incrementay(void* arg)
- {
- for(;;) {
- pthread_mutex_lock(&mutex);
- if (y > 200) {
- printf("\t\tty ha finito\n");
- pthread_mutex_unlock(&mutex);
- pthread_exit(NULL);
- }
- if (y > x) {
- if (addormentato == 1) {
- printf("x %d < y %d\n", x, y);
- printf("\t\tthread ty: BASTA RONFARE\n");
- pthread_cond_signal(&cond);
- }
- }
- y++;
- printf("\t\tthread ty: y = %d\n", y);
- pthread_mutex_unlock(&mutex);
- usleep(50000L);
- }
- }
- int main(int argc, char** argv)
- {
- int * presult; // per valore restituito da pthread_exit(tx,...)
- x = 0;
- y = 5;
- pthread_t tx, ty;
- pthread_create(&tx, NULL, incrementax, NULL );
- pthread_create(&ty, NULL, incrementay, NULL);
- pthread_join(tx, (void **) &presult);
- pthread_join(ty, NULL);
- printf("thread terminati, tx ritorna %d\n", *presult);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement