Skip to content
Snippets Groups Projects
Commit 63695ca5 authored by Mactavish's avatar Mactavish
Browse files

add approximate-counter exercise

parent 0042425c
Branches
No related tags found
No related merge requests found
#include "counter.h"
void init_counter(counter_t *c, int threshold, int num_cpu) {
// TODO: Implement this function
}
void update_counter(counter_t *c, int t_id, int amount) {
// TODO: Implement this function
}
int get_counter_val(counter_t *c) {
pthread_mutex_lock(&c->glock);
int val = c->global;
pthread_mutex_unlock(&c->glock);
return val;
}
void sync_counter(counter_t *c) {
// TODO: Implement this function
}
void destroy_counter(counter_t *c) {
// TODO: Implement this function
}
#include <pthread.h>
#include <stdlib.h>
typedef struct __counter_t {
int num_cpu; // number of cpus
long long global; // global count
pthread_mutex_t glock; // global lock
long *local; // local count (per cpu)
pthread_mutex_t *llock; // ... and locks
int threshold; // update frequency
} counter_t;
void init_counter(counter_t *c, int threshold, int num_cpu);
void update_counter(counter_t * c, int t_id, int amount);
int get_counter_val(counter_t *c);
void sync_counter(counter_t *c);
void destroy_counter(counter_t *c);
#include "counter.h"
#include <stdio.h>
#include <unistd.h>
#define COUNT_LIMIT 10000000
#define THREADSHOLD 1024
counter_t counter;
void *worker(void *t_id) {
printf("Thread %d started\n", (int) t_id);
for (int i = 0; i < COUNT_LIMIT; i++) {
update_counter(&counter, (int) t_id, 1);
}
}
int main() {
long num_cpus = sysconf(_SC_NPROCESSORS_ONLN);
printf("Number of CPUs: %ld\n", num_cpus);
pthread_t *threads = malloc(num_cpus * sizeof(pthread_t));
init_counter(&counter, THREADSHOLD, num_cpus);
for (int i = 0; i < num_cpus; i++) {
pthread_create(&threads[i], NULL, worker, (void *) i);
}
for (int i = 0; i < num_cpus; i++) {
pthread_join(threads[i], NULL);
}
sync_counter(&counter);
printf("Counter value: %d\n", get_counter_val(&counter));
destroy_counter(&counter);
return 0;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment