/
bvs22
/
draft
Обзор
Документация
Войти
/
bvs22
/
draft
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
threads/total_counter.c
41 строка
694 B
bvs22
add total counter using pthread
30 ноя 2024, 14:18
30 ноя 2024, 14:18
0d43673
Код
Авторство
О чём код?
#include <stdio.h> #include <pthread.h> #define COUNT_CYCLES 1000 #define SIZE_COUNTER 3 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int total_counter = {0}; void *counter_func(void *args) { pthread_mutex_lock(&mutex); for (int i = 0; i < COUNT_CYCLES; i++) { total_counter++; } pthread_mutex_unlock(&mutex); pthread_exit(NULL); } int main() { pthread_t counter[SIZE_COUNTER]; for (int i = 0; i < SIZE_COUNTER; i++) { pthread_create(&counter[i], NULL, counter_func, NULL); } for (int i = 0; i < SIZE_COUNTER; i++) { pthread_join(counter[i], NULL); } printf("%d\n", total_counter); return 0; }