Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c1904f9ef2 |
55
.gitignore
vendored
55
.gitignore
vendored
@ -1,55 +0,0 @@
|
||||
# Prerequisites
|
||||
*.d
|
||||
|
||||
# Object files
|
||||
*.o
|
||||
*.ko
|
||||
*.obj
|
||||
*.elf
|
||||
|
||||
# Linker output
|
||||
*.ilk
|
||||
*.map
|
||||
*.exp
|
||||
|
||||
# Precompiled Headers
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
# Libraries
|
||||
*.lib
|
||||
*.a
|
||||
*.la
|
||||
*.lo
|
||||
|
||||
# Shared objects (inc. Windows DLLs)
|
||||
*.dll
|
||||
*.so
|
||||
*.so.*
|
||||
*.dylib
|
||||
|
||||
# Executables
|
||||
*.exe
|
||||
*.out
|
||||
*.app
|
||||
*.i*86
|
||||
*.x86_64
|
||||
*.hex
|
||||
|
||||
# Debug files
|
||||
*.dSYM/
|
||||
*.su
|
||||
*.idb
|
||||
*.pdb
|
||||
|
||||
# Kernel Module Compile Results
|
||||
*.mod*
|
||||
*.cmd
|
||||
.tmp_versions/
|
||||
modules.order
|
||||
Module.symvers
|
||||
Mkfile.old
|
||||
dkms.conf
|
||||
|
||||
# debug information files
|
||||
*.dwo
|
||||
2
DBs/.gitignore
vendored
Normal file
2
DBs/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
*.pdf
|
||||
|
||||
23
DBs/README.md
Normal file
23
DBs/README.md
Normal file
@ -0,0 +1,23 @@
|
||||
# Базы данных
|
||||
|
||||
Тут будут лежать лабы по PostgreSQL.
|
||||
|
||||
## Структура
|
||||
|
||||
В корне есть файл `main.typ`. Его можно скомпилировать с помощью
|
||||
|
||||
```
|
||||
typst c main.typ
|
||||
```
|
||||
|
||||
Внутри него есть директивы включения файлов с лабами.
|
||||
|
||||
В каждой директории `^lab\d+\/$` есть как минимум один файл `main.typ`,
|
||||
которые и включаются в корневой `main.typ`. Это позволяет формировать структурированный отчет
|
||||
для курсовика.
|
||||
|
||||
## Окружение
|
||||
|
||||
- Я использую `docker.io/library/postgres:16.10-alpine3.2` в контейнере `podman`
|
||||
- Для работы с БД - `pgcli`
|
||||
|
||||
72
DBs/lab1/main.typ
Normal file
72
DBs/lab1/main.typ
Normal file
@ -0,0 +1,72 @@
|
||||
= Работа №1. Создание базы данных.
|
||||
|
||||
== Смена пароля
|
||||
|
||||
```sql
|
||||
ALTER USER surimi WITH PASSWORD 'trio';
|
||||
```
|
||||
|
||||
== Создание таблиц
|
||||
|
||||
```sql
|
||||
-- create
|
||||
CREATE TABLE auto_personnel (
|
||||
id serial primary key,
|
||||
first_name varchar(255),
|
||||
last_name varchar(255),
|
||||
father_name varchar(255)
|
||||
);
|
||||
COMMENT ON TABLE auto_personnel IS 'Сотрудники автопарка';
|
||||
|
||||
CREATE TABLE auto (
|
||||
id serial primary key,
|
||||
num varchar(255),
|
||||
color varchar(255),
|
||||
mark varchar(255)
|
||||
);
|
||||
COMMENT ON TABLE auto IS 'Автомобили автопарка';
|
||||
|
||||
CREATE TABLE routes (
|
||||
id serial primary key,
|
||||
name varchar(255)
|
||||
);
|
||||
COMMENT ON TABLE routes IS 'Маршруты';
|
||||
|
||||
CREATE TABLE journal (
|
||||
id serial primary key,
|
||||
time_out timestamp with time zone,
|
||||
time_in timestamp with time zone
|
||||
);
|
||||
COMMENT ON TABLE journal IS 'Журнал оператора';
|
||||
```
|
||||
|
||||
== Создание связей
|
||||
|
||||
```sql
|
||||
ALTER TABLE journal ADD COLUMN route_id INTEGER NOT NULL CONSTRAINT fk_journal_routes REFERENCES routes(id);
|
||||
ALTER TABLE journal ADD COLUMN auto_id INTEGER NOT NULL CONSTRAINT fk_journal_auto REFERENCES auto(id);
|
||||
ALTER TABLE auto ADD COLUMN personnel_id INTEGER NOT NULL CONSTRAINT fk_auto_auto_personnel REFERENCES auto_personnel(id);
|
||||
```
|
||||
|
||||
== Удаление таблиц
|
||||
|
||||
```sql
|
||||
-- drop
|
||||
DROP TABLE auto_personnel CASCADE;
|
||||
DROP TABLE auto CASCADE;
|
||||
DROP TABLE routes CASCADE;
|
||||
DROP TABLE journal CASCADE;
|
||||
```
|
||||
|
||||
== Бекап
|
||||
|
||||
```sh
|
||||
podman exec postgresinstance-postgres-1 pg_dump postgres -U surimi > dump.sql
|
||||
```
|
||||
|
||||
== Восстановление
|
||||
|
||||
```sh
|
||||
podman exec -i postgresinstance-postgres-1 psql -U surimi -d postgres < dump.sql
|
||||
```
|
||||
|
||||
10
DBs/main.typ
Normal file
10
DBs/main.typ
Normal file
@ -0,0 +1,10 @@
|
||||
#import "@preview/ilm:1.4.1": *
|
||||
|
||||
#set text(lang: "ru")
|
||||
|
||||
#show: ilm.with(
|
||||
title: [Базы данных],
|
||||
author: "Марк Железняков",
|
||||
)
|
||||
|
||||
#include "lab1/main.typ"
|
||||
@ -1 +0,0 @@
|
||||
Здесь я не буду оформлять первый уровень, потому что он фактически выглядит как копипаста. Возможно я потом докину его
|
||||
@ -1,12 +0,0 @@
|
||||
targets = main
|
||||
all: $(targets)
|
||||
|
||||
main: main.o buff.o
|
||||
$(CC) -o $@ $^ $(CFLAGS)
|
||||
|
||||
%.o: %.c
|
||||
$(CC) -c $^ -o $@ $(CFLAGS)
|
||||
|
||||
clean:
|
||||
rm -f $(targets)
|
||||
rm -f *.o
|
||||
@ -1,5 +0,0 @@
|
||||
Во продвинутом уровне задания необходимо было реализовать паттерн producer-consumer. Заводится буффер определенного размера, а также потоки, которые в него что-то кладут и потоки, которые из него что-то берут.
|
||||
|
||||
Внутри buff.c сокрыта вся магия по синхронизации буффера, постановке на него предметов и прочего. В main же только создаются потоки. Я решил, что producer будет создавать "ключи", а consumer будет их печатать
|
||||
|
||||
Чтобы не решать проблемы с зачисткой буффера в конце, семафоры поставлены на таймаут, по истечении которого поток вылетит
|
||||
@ -1,142 +0,0 @@
|
||||
#include <stdio.h>
|
||||
#include <semaphore.h>
|
||||
#include <string.h>
|
||||
#include <pthread.h>
|
||||
#include <errno.h>
|
||||
|
||||
#include "buff.h"
|
||||
|
||||
#define NBUFF 32
|
||||
#define TIMEOUT_SECS 5
|
||||
#define TIMEOUT_NSECS 0
|
||||
|
||||
#define ARR_SIZE(arr) (sizeof(arr)/sizeof(arr[0]))
|
||||
|
||||
static void __zero_msg(struct message *msg)
|
||||
{
|
||||
memset(msg->msg, 0, sizeof(msg->msg));
|
||||
}
|
||||
|
||||
static void __copy_msg(struct message *dest, const struct message *src)
|
||||
{
|
||||
memcpy(dest->msg, src->msg, sizeof(src->msg));
|
||||
}
|
||||
|
||||
static struct {
|
||||
pthread_mutex_t msgs_lock;
|
||||
sem_t nstored;
|
||||
sem_t nempty;
|
||||
struct message msgs[NBUFF];
|
||||
size_t cidx; //< consumer offset
|
||||
size_t pidx; //< producer offset
|
||||
} buf = {0};
|
||||
|
||||
int buf_init(void)
|
||||
{
|
||||
int ret = 0;
|
||||
ret = sem_init(&buf.nstored, 0, 0);
|
||||
if (ret) {
|
||||
ret = -EFAULT;
|
||||
goto error;
|
||||
}
|
||||
ret = sem_init(&buf.nempty, 0, ARR_SIZE(buf.msgs));
|
||||
if (ret) {
|
||||
ret = -EFAULT;
|
||||
goto destroy_nstored;
|
||||
}
|
||||
ret = pthread_mutex_init(&buf.msgs_lock, NULL);
|
||||
if (ret) {
|
||||
goto destroy_nempty;
|
||||
}
|
||||
return 0;
|
||||
|
||||
destroy_nempty:
|
||||
sem_destroy(&buf.nempty);
|
||||
destroy_nstored:
|
||||
sem_destroy(&buf.nstored);
|
||||
error:
|
||||
return ret;
|
||||
};
|
||||
|
||||
int buf_deinit(void)
|
||||
{
|
||||
int ret = 0, tmp_ret;
|
||||
if ((tmp_ret = pthread_mutex_destroy(&buf.msgs_lock))) ret = tmp_ret;
|
||||
if ((tmp_ret = sem_destroy(&buf.nempty))) ret = tmp_ret;
|
||||
if ((tmp_ret = sem_destroy(&buf.nstored))) ret = tmp_ret;
|
||||
return ret;
|
||||
}
|
||||
|
||||
#define __buf_wrap_idx(idx) (idx % ARR_SIZE(buf.msgs))
|
||||
#define __buf_consume_ptr (&buf.msgs[__buf_wrap_idx(buf.cidx)])
|
||||
#define __buf_produce_ptr (&buf.msgs[__buf_wrap_idx(buf.pidx)])
|
||||
|
||||
static int __timeout_to_abs(struct timespec *ts, time_t secs, ssize_t nsec)
|
||||
{
|
||||
int ret = timespec_get(ts, TIME_UTC);
|
||||
if (ret != TIME_UTC) return -EFAULT;
|
||||
ts->tv_sec += secs;
|
||||
ts->tv_nsec += nsec;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int __sem_timedwait_rel(sem_t *sem, time_t secs, ssize_t nsecs)
|
||||
{
|
||||
int ret;
|
||||
struct timespec sem_timeout;
|
||||
ret = __timeout_to_abs(&sem_timeout, secs, nsecs);
|
||||
if (ret) return ret;
|
||||
return sem_timedwait(sem, &sem_timeout);
|
||||
}
|
||||
|
||||
static int __buf_consume(struct message *dest)
|
||||
{
|
||||
int ret = pthread_mutex_lock(&buf.msgs_lock);
|
||||
if (ret) {
|
||||
return -EFAULT;
|
||||
}
|
||||
__copy_msg(dest, __buf_consume_ptr);
|
||||
__zero_msg(__buf_consume_ptr);
|
||||
buf.cidx++;
|
||||
// Осозннано игнорируем ошибки
|
||||
ret = pthread_mutex_unlock(&buf.msgs_lock);
|
||||
return ret;
|
||||
}
|
||||
|
||||
int buf_consume(struct message *dest)
|
||||
{
|
||||
int ret = 0;
|
||||
int semval = 0;
|
||||
ret = __sem_timedwait_rel(&buf.nstored, TIMEOUT_SECS, TIMEOUT_NSECS);
|
||||
if (ret) return ret;
|
||||
|
||||
ret = __buf_consume(dest);
|
||||
if (ret) return ret;
|
||||
|
||||
ret = sem_post(&buf.nempty);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static int __buf_push(const struct message *src)
|
||||
{
|
||||
int ret = pthread_mutex_lock(&buf.msgs_lock);
|
||||
if (ret) {
|
||||
return -EFAULT;
|
||||
}
|
||||
__copy_msg(__buf_produce_ptr, src);
|
||||
buf.pidx++;
|
||||
ret = pthread_mutex_unlock(&buf.msgs_lock);
|
||||
return ret;
|
||||
}
|
||||
|
||||
int buf_push(const struct message *src)
|
||||
{
|
||||
int ret = 0;
|
||||
ret = __sem_timedwait_rel(&buf.nempty, TIMEOUT_SECS, TIMEOUT_NSECS);
|
||||
if (ret) return ret;
|
||||
|
||||
ret = __buf_push(src);
|
||||
if (ret) return ret;
|
||||
|
||||
return sem_post(&buf.nstored);
|
||||
}
|
||||
@ -1,16 +0,0 @@
|
||||
#ifndef BUFF_H_
|
||||
#define BUFF_H_
|
||||
|
||||
#define MSG_MAX_LEN 256
|
||||
|
||||
struct message {
|
||||
char msg[MSG_MAX_LEN];
|
||||
};
|
||||
|
||||
int buf_init(void);
|
||||
int buf_deinit(void);
|
||||
|
||||
int buf_consume(struct message *dest);
|
||||
int buf_push(const struct message *src);
|
||||
|
||||
#endif
|
||||
@ -1,105 +0,0 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <pthread.h>
|
||||
#include <stdbool.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "buff.h"
|
||||
|
||||
#define ERR_PTR ((void *)1)
|
||||
#define VOID_CAST(num) ((void *) num)
|
||||
|
||||
#define N_PRODUCERS 16
|
||||
#define N_CONSUMERS 1
|
||||
#define KEY_LEN 32 // len in chars
|
||||
|
||||
const char key_syms[] = "abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ"
|
||||
"1234567890";
|
||||
|
||||
#define ALPHABET_SIZE (sizeof(key_syms) - 1)
|
||||
|
||||
pthread_t consumers[N_CONSUMERS] = {0};
|
||||
pthread_t producers[N_PRODUCERS] = {0};
|
||||
|
||||
/**
|
||||
* Создает "ключи" - наборы "случайных" символов из
|
||||
* списка допустимых
|
||||
*/
|
||||
void get_key(char key_dest[KEY_LEN])
|
||||
{
|
||||
for (size_t i = 0; i < KEY_LEN; i++) {
|
||||
size_t sym_idx = rand() % ALPHABET_SIZE;
|
||||
key_dest[i] = key_syms[sym_idx];
|
||||
}
|
||||
}
|
||||
|
||||
volatile bool run = true;
|
||||
|
||||
void *producer_routine(void *arg)
|
||||
{
|
||||
size_t pidx = (size_t) arg;
|
||||
struct message msg = {0};
|
||||
while (run) {
|
||||
get_key(msg.msg);
|
||||
if (buf_push(&msg)) pthread_exit(ERR_PTR);
|
||||
printf("[p%lu] pushed new key\n", pidx);
|
||||
sleep(1);
|
||||
}
|
||||
pthread_exit(NULL);
|
||||
}
|
||||
|
||||
void *consumer_routine(void *arg)
|
||||
{
|
||||
size_t cidx = (size_t) arg;
|
||||
struct message msg = {0};
|
||||
while (run) {
|
||||
if (buf_consume(&msg)) pthread_exit(ERR_PTR);
|
||||
printf("[c%lu] obtained key %s\n", cidx, msg.msg);
|
||||
sleep(1);
|
||||
}
|
||||
pthread_exit(NULL);
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
if (buf_init()) {
|
||||
printf("failed to init work buffer\n");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < N_PRODUCERS; i++) {
|
||||
if (pthread_create(&producers[i], NULL,
|
||||
producer_routine, VOID_CAST(i))) {
|
||||
printf("Failed to create enough consumer threads\n");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
}
|
||||
for (size_t i = 0; i < N_CONSUMERS; i++) {
|
||||
if (pthread_create(&consumers[i], NULL,
|
||||
consumer_routine, VOID_CAST(i))) {
|
||||
printf("Failed to create enough consumer threads\n");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
sleep(10);
|
||||
run = false;
|
||||
|
||||
void *ret = NULL;
|
||||
for (size_t i = 0; i < N_PRODUCERS; i++) {
|
||||
if (pthread_join(producers[i], &ret)) {
|
||||
printf("failed to join producer");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
}
|
||||
for (size_t i = 0; i < N_CONSUMERS; i++) {
|
||||
if (pthread_join(consumers[i], &ret)) {
|
||||
printf("failed to join consumer");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
}
|
||||
// не используем разделяемые ресурсы, так что код возврата
|
||||
// можно игнорировать, linux справится
|
||||
buf_deinit();
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
Reference in New Issue
Block a user