Files
AwesomePolytech/OSs/lab2/unix/part-B/main.c
ElectronixTM 5cdf8871be feat(lab2): unix lab2 done
Lab 2 is in fact the first lab in the set of ones we actually do. It's
not particularly hard, but consumed some time for me
2025-09-10 23:41:03 +03:00

54 lines
1.3 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* "THE CHEESE-WARE LICENSE" (Revision 1):
* <ElectronixTM> wrote this file. As long as you retain this notice
* you can do whatever you want with this stuff. If we meet some day,
* and you think this stuff is worth it, you can buy me some cheese
* in return
*/
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
volatile unsigned long long global = 0;
#define NR_THREADS 4
#define GLOBAL_STOP_VALUE 15
pthread_t threads[NR_THREADS] = {0};
void *thread_routine(void* args)
{
size_t arg = *((size_t *) args);
// Так как на глобальном счетчике нет синхронизации,
// количество выводов в консоль можен не совпадать с
// GLOBAL_STOP_VALUE
while (global < GLOBAL_STOP_VALUE) {
printf("Hello from thread %lu\n", arg);
global += 1;
sleep(5);
}
pthread_exit(NULL);
}
int main()
{
for (size_t i = 0; i < NR_THREADS; i++) {
size_t *arg = malloc(sizeof(*arg));
assert(arg);
*arg = i;
pthread_create(&threads[i], NULL, thread_routine, arg);
}
int ret;
for (size_t i = 0; i < NR_THREADS; i++) {
ret = pthread_join(threads[i], NULL);
if (ret) {
break;
}
}
return 0;
}