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
54 lines
1.3 KiB
C
54 lines
1.3 KiB
C
/*
|
||
* "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;
|
||
}
|