123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152 |
- #include <errno.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <pthread.h>
- #define NUM_THREADS 5
- void *search(void *);
- void print_it(void *);
- pthread_t threads[NUM_THREADS];
- pthread_mutex_t lock;
- int tries;
- volatile int started;
- int main(int argc, char ** argv)
- {
- unsigned long i;
- unsigned long pid;
-
- pid = getpid();
- printf("Searching for the number = %ld...\n", pid);
-
- pthread_mutex_init(&lock, NULL);
-
- for (started=0; started<NUM_THREADS; started++)
- pthread_create(&threads[started], NULL, search, (void *)pid);
-
- for (i=0; i<NUM_THREADS; i++)
- pthread_join(threads[i], NULL);
- printf("It took %d tries to find the number.\n", tries);
-
- return 0;
- }
- void print_it(void *arg)
- {
- int *try = (int *) arg;
- pthread_t tid;
-
- tid = pthread_self();
-
- printf("Thread %lx was canceled on its %d try.\n", tid, *try);
- }
- void *search(void *arg)
- {
- unsigned long num = (unsigned long) arg;
- unsigned long i, j, ntries;
- pthread_t tid;
-
- tid = pthread_self();
-
-
-
- while (pthread_mutex_trylock(&lock) == EBUSY)
- pthread_testcancel();
- srand((int)tid);
- i = rand() & 0xFFFFFF;
- pthread_mutex_unlock(&lock);
- ntries = 0;
-
- pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
- pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
- while (started < NUM_THREADS)
- sched_yield ();
-
-
- pthread_cleanup_push(print_it, (void *)&ntries);
-
- while (1) {
- i = (i + 1) & 0xFFFFFF;
- ntries++;
-
- if (num == i) {
-
- while (pthread_mutex_trylock(&lock) == EBUSY)
- pthread_testcancel();
-
- tries = ntries;
- printf("Thread %lx found the number!\n", tid);
-
- for (j=0; j<NUM_THREADS; j++)
- if (threads[j] != tid) pthread_cancel(threads[j]);
-
- break;
- }
-
- if (ntries % 100 == 0) {
- pthread_testcancel();
- }
- }
-
- pthread_cleanup_pop(0);
- return((void *)0);
- }
|