Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <pthread.h>
- const long kSize = 1e7L;
- long ctr = 0;
- pthread_mutex_t mtx;
- void *func1(void *a) {
- for (long i = 0; i < kSize; ++i) {
- pthread_mutex_lock(&mtx);
- ++ctr;
- pthread_mutex_unlock(&mtx);
- }
- return NULL;
- }
- void *func2(void *a) {
- for (long i = 0; i < kSize; ++i) {
- pthread_mutex_lock(&mtx);
- --ctr;
- pthread_mutex_unlock(&mtx);
- }
- return NULL;
- }
- int main(void) {
- clock_t start = clock();
- if (pthread_mutex_init(&mtx, PTHREAD_MUTEX_NORMAL) != 0) {
- fprintf(stderr, "pthread_mutex_init(): Error.\n");
- return -1;
- }
- pthread_t th1, th2;
- if (pthread_create(&th1, NULL, func1, NULL) != 0 ||
- pthread_create(&th2, NULL, func2, NULL) != 0) {
- fprintf(stderr, "pthread_create(): Error.\n");
- return -1;
- }
- pthread_join(th1, NULL);
- pthread_join(th2, NULL);
- pthread_mutex_destroy(&mtx);
- printf("Counter: %ld \t CPU time: %ld ms\n",
- ctr, (clock() - start) * 1000L / CLOCKS_PER_SEC);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement