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
This commit is contained in:
53
OSs/lab2/unix/part-B/main.c
Normal file
53
OSs/lab2/unix/part-B/main.c
Normal file
@ -0,0 +1,53 @@
|
||||
/*
|
||||
* "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;
|
||||
}
|
||||
Reference in New Issue
Block a user