Files
OS-LABS/2/main.cpp
T

160 lines
4.7 KiB
C++

#include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <random>
#include <pthread.h>
#include <sys/time.h>
#include <unistd.h>
#include <sstream>
// ================= СТРУКТУРЫ =================
constexpr int NIL = -1;
struct Node {
int value;
int next;
};
struct SortResult {
int head;
long long comparisons;
};
struct Args {
Node* pool;
int head;
int depth;
SortResult* res_out;
};
// ================= ГЛОБАЛЬНЫЕ ПЕРЕМЕННЫЕ =================
int active_threads = 0;
int max_threads = 4;
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;
// ================= УТИЛИТЫ =================
std::string now() {
timeval tv{};
gettimeofday(&tv, nullptr);
std::ostringstream oss;
oss << tv.tv_sec << "." << std::setfill('0') << std::setw(6) << tv.tv_usec;
return oss.str();
}
// Формат лога адаптирован под ваш скрипт analyze_log.py
void log_event(const std::string& type, int head, int depth) {
pthread_mutex_lock(&log_mutex);
// Используем head как идентификатор диапазона для парсера
std::cout << type << " TID=" << pthread_self()
<< " depth=" << depth
<< " range=[" << head << "," << head << "]"
<< " time=" << now() << std::endl;
pthread_mutex_unlock(&log_mutex);
}
// ================= ЛОГИКА СПИСКА =================
void split_list(Node* pool, int head, int& left, int& right) {
if (head == NIL || pool[head].next == NIL) {
left = head; right = NIL; return;
}
int slow = head, fast = pool[head].next;
while (fast != NIL) {
fast = pool[fast].next;
if (fast != NIL) { slow = pool[slow].next; fast = pool[fast].next; }
}
left = head;
right = pool[slow].next;
pool[slow].next = NIL;
}
SortResult merge_lists(Node* pool, int l, int r) {
long long comps = 0;
if (l == NIL) return {r, 0};
if (r == NIL) return {l, 0};
int res_head = NIL, tail = NIL;
auto append = [&](int idx) {
if (res_head == NIL) res_head = tail = idx;
else { pool[tail].next = idx; tail = idx; }
};
while (l != NIL && r != NIL) {
comps++;
if (pool[l].value <= pool[r].value) { int n = pool[l].next; append(l); l = n; }
else { int n = pool[r].next; append(r); r = n; }
}
if (l != NIL) pool[tail].next = l;
if (r != NIL) pool[tail].next = r;
return {res_head, comps};
}
// ================= РЕКУРСИЯ =================
SortResult parallel_list_sort(Node* pool, int head, int depth);
void* thread_func(void* arg) {
Args* a = (Args*)arg;
*(a->res_out) = parallel_list_sort(a->pool, a->head, a->depth);
return nullptr;
}
SortResult parallel_list_sort(Node* pool, int head, int depth) {
log_event("START", head, depth);
if (head == NIL || pool[head].next == NIL) {
log_event("END", head, depth);
return {head, 0};
}
int left_p, right_p;
split_list(pool, head, left_p, right_p);
pthread_t tid;
bool spawned = false;
SortResult res_right = {NIL, 0};
pthread_mutex_lock(&counter_mutex);
if (active_threads < max_threads) {
active_threads++;
spawned = true;
}
pthread_mutex_unlock(&counter_mutex);
if (spawned) {
Args* args = new Args{pool, right_p, depth + 1, &res_right};
pthread_create(&tid, nullptr, thread_func, args);
SortResult res_left = parallel_list_sort(pool, left_p, depth + 1);
pthread_join(tid, nullptr);
pthread_mutex_lock(&counter_mutex);
active_threads--;
pthread_mutex_unlock(&counter_mutex);
SortResult m = merge_lists(pool, res_left.head, res_right.head);
delete args;
log_event("END", m.head, depth);
return {m.head, res_left.comparisons + res_right.comparisons + m.comparisons};
} else {
SortResult res_left = parallel_list_sort(pool, left_p, depth + 1);
SortResult res_r_seq = parallel_list_sort(pool, right_p, depth + 1);
SortResult m = merge_lists(pool, res_left.head, res_r_seq.head);
log_event("END", m.head, depth);
return {m.head, res_left.comparisons + res_r_seq.comparisons + m.comparisons};
}
}
int main(int argc, char* argv[]) {
int n = 10000;
if (argc >= 2) n = std::atoi(argv[1]);
if (argc >= 3) max_threads = std::atoi(argv[2]);
std::vector<Node> pool(n);
std::mt19937 rng(time(0));
for (int i = 0; i < n; i++) {
pool[i].value = rng() % 100000;
pool[i].next = (i == n - 1) ? NIL : i + 1;
}
parallel_list_sort(pool.data(), 0, 0);
return 0;
}