include pthread h include stdio h include stdlib
#include <pthread. h> #include <stdio. h> #include <stdlib. h> #define NITER 100000 long count = 0; void * Thread. Add(void * a) { long i, tmp; for(i = 0; i < NITER; i++) { count++; } } int main(int argc, char * argv[]) { pthread_t tid 1, tid 2; pthread_create(&tid 1, NULL, Thread. Add, NULL); pthread_create(&tid 2, NULL, Thread. Add, NULL); pthread_join(tid 1, NULL); /* wait for the thread 1 to finish */ pthread_join(tid 2, NULL); /* wait for the thread 2 to finish */ if (count < 2 * NITER) printf("n BOOM! count is [%ld], should be %ldn", count, 2*NITER); else printf("n OK! count is [%ld]n", count); pthread_exit(NULL); } 1 BOOM! count is [1971985225], should be 200000
mutex (1) פעולות על מנעולי #include <pthread. h> : לפני השימוש mutex • אתחול int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutex_attr_t *mutexattr); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutexattr_t mattr; int ret; /* initialize a mutex to its default value */ ret = pthread_mutex_init(&mutex, NULL); בתום השימוש mutex • פינוי int pthread_mutex_destroy(pthread_mutex_t *mutex); אבל נעול , מאותחל -mutex – הפעולה נכשלת אם ה 4
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutexattr_t mattr; int ret; /* initialize a mutex to its default value */ ret = pthread_mutex_init(&mutex, NULL); default attributes PTHREAD_MUTEX_INITIALIZER or PTHREAD_RMUTEX_INITIALIZER (for recursive mutexes). 5
#include <pthread. h> #include <stdio. h> #include <stdlib. h> #define NITER 100000 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; long count = 0, count 1 = 0; void * Thread. Add(void * a) { for(long i = 0; i < NITER; i++) { pthread_mutex_lock( &mutex ); count++; pthread_mutex_unlock( &mutex ); for(i = 0; i < NITER; i++) count++; } } int main(int argc, char * argv[]) { pthread_t tid 1, tid 2; pthread_mutex_init(&mutex, NULL); pthread_create(&tid 1, NULL, Thread. Add, NULL); pthread_create(&tid 2, NULL, Thread. Add, NULL); pthread_join(tid 1, NULL); /* wait for the thread 1 to finish */ pthread_join(tid 2, NULL); /* wait for the thread 2 to finish */ if (count < 2 * NITER) printf("n BOOM! count is [%ld], should be %ldn", count, 2*NITER); else printf("n OK! count is [%ld]n", count); if (count < 2 * NITER) printf("n BOOM! count 1 is [%ld], should be %ldn", count 1, 2*NITER); else printf("n OK! count 1 is [%ld]n", count 1); } pthread_exit(NULL); 9 OK! count is [200000] BOOM! count 1 is [16372624], should be 200000
- Slides: 11