shared-memory-in-c/threads/main.c

55 lines
1.1 KiB
C

#include <string.h>
#include <stdio.h>
#include <pthread.h>
struct shared_data {
pthread_mutex_t mutex;
int counter;
};
struct thread_args {
const char *name;
struct shared_data *shared;
};
void *thread_callback(void *p) {
struct thread_args *args = p;
struct shared_data *data = args->shared;
for (int i = 0; i < 100000; i++) {
if (pthread_mutex_lock(&data->mutex) != 0) {
perror("pthread_mutex_lock");
}
data->counter++;
if (pthread_mutex_unlock(&data->mutex) != 0) {
perror("pthread_mutex_unlock");
}
}
return NULL;
}
int main() {
struct shared_data shared_data = { 0 };
if (pthread_mutex_init(&shared_data.mutex, NULL) < 0) {
printf("Failed to initialise mutex\n");
return -1;
}
pthread_t thread1;
struct thread_args args1 = { "Thread 1", &shared_data };
pthread_create(&thread1, NULL, thread_callback, &args1);
pthread_t thread2;
struct thread_args args2 = { "Thread 2", &shared_data };
pthread_create(&thread2, NULL, thread_callback, &args2);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Counter is %d\n", shared_data.counter);
}