Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <time.h>
- #include <stdint.h>
- #define _NUMBER_OF_FLIPS 1
- #define _NUMBER_OF_COINS 20
- #define _NUMBER_OF_PEOPLE 10000
- char coins[_NUMBER_OF_COINS];
- pthread_mutex_t lock;
- pthread_mutex_t locks[_NUMBER_OF_COINS];
- struct person {
- pthread_t tid;
- };
- struct person people[_NUMBER_OF_PEOPLE];
- void *flip_coins_first(void *arg) {
- pthread_mutex_lock(&lock);
- for (int i = 0; i < _NUMBER_OF_COINS; i++) {
- for (int j = 0; j < _NUMBER_OF_FLIPS; j++) {
- if (coins[i] == 'X') {
- coins[i] = '0';
- } else {
- coins[i] = 'X';
- }
- }
- }
- pthread_mutex_unlock(&lock);
- return NULL;
- }
- void *flip_coins_second(void *arg) {
- int idx = (intptr_t) arg;
- pthread_mutex_lock(&locks[idx]);
- for (int j = 0; j < _NUMBER_OF_FLIPS; j++) {
- if (coins[idx] == 'X') {
- coins[idx] = '0';
- } else {
- coins[idx] = 'X';
- }
- }
- pthread_mutex_unlock(&locks[idx]);
- return NULL;
- }
- int main(int argc, char *argv[]) {
- pthread_mutex_init(&lock, NULL);
- for (int i = 0; i < _NUMBER_OF_COINS; i++) {
- pthread_mutex_init(&locks[i], NULL);
- }
- pthread_t orig_tid = pthread_self();
- for (int i = 0; i < _NUMBER_OF_COINS; i++) {
- coins[i] = '0';
- }
- clock_t begin = clock();
- printf("coins: %s (start - global lock)\n", coins);
- for (int i = 0; i < _NUMBER_OF_PEOPLE; i++) {
- int err = pthread_create(&people[i].tid, NULL, flip_coins_first,
- NULL);
- if (err != 0) {
- printf("Can't spawn thread %d", i);
- }
- }
- for (int i = 0; i < _NUMBER_OF_PEOPLE; i++) {
- (void) pthread_join(people[i].tid, NULL);
- }
- printf("coins: %s (end - global lock)\n", coins);
- pthread_mutex_destroy(&lock);
- clock_t end = clock();
- double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
- printf("%d threads x %d flips: %f ms\n\n", _NUMBER_OF_PEOPLE,
- _NUMBER_OF_FLIPS, time_spent);
- begin = clock();
- printf("coins: %s (start - local lock)\n", coins);
- for (int i = 0; i < _NUMBER_OF_PEOPLE; i++) {
- for (int j = 0; j < _NUMBER_OF_COINS; j++) {
- int err = pthread_create(&people[i].tid, NULL, flip_coins_second,
- (void *) (intptr_t) j);
- if (err != 0) {
- printf("Can't spawn thread %d", i);
- }
- }
- }
- for (int i = 0; i < _NUMBER_OF_PEOPLE; i++) {
- (void) pthread_join(people[i].tid, NULL);
- }
- printf("coins: %s (end - local lock)\n", coins);
- end = clock();
- time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
- printf("%d threads x %d flips: %f ms\n", _NUMBER_OF_PEOPLE,
- _NUMBER_OF_FLIPS, time_spent);
- for (int i = 0; i < _NUMBER_OF_COINS; i++) {
- pthread_mutex_destroy(&locks[i]);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement