This commit is contained in:
justuser-31 2025-02-11 10:16:05 +03:00
parent 163188a814
commit 3a07a9b5ed
7 changed files with 111 additions and 0 deletions

2
examples/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
a.out
a.exe

11
examples/comp_run_lin.sh Executable file
View File

@ -0,0 +1,11 @@
echo -n "File: "
read file
while true
do
clear && gcc $file && ./a.out
echo "----------------"
echo "Programm ended."
echo "----------------"
read _
done

11
examples/comp_run_win.sh Executable file
View File

@ -0,0 +1,11 @@
echo -n "File: "
read file
while true
do
clear && x86_64-w64-mingw32-gcc $file && wine a.exe
echo "----------------"
echo "Programm ended."
echo "----------------"
read _
done

26
examples/threads.c Normal file
View File

@ -0,0 +1,26 @@
#include <stdio.h>
#include <stdlib.h>
#include "../libs/threads.h"
void* task() {
while (1) {
printf("Background task running\n");
wait(1);
}
return NULL;
}
int main() {
void* thread_handle;
start_thread(&thread_handle, task);
printf("Main program continues\n");
wait(5);
kill_thread(thread_handle);
printf("Background task killed\n");
return 0;
}

10
examples/wait.c Normal file
View File

@ -0,0 +1,10 @@
#include <stdio.h>
#include "../libs/time.h"
int main() {
printf("Wait 5 seconds...\n");
wait(5);
return 0;
}

38
libs/threads.h Normal file
View File

@ -0,0 +1,38 @@
#ifdef _WIN32
#include <windows.h>
#else
#include <pthread.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include "time.h"
void start_thread(void** thread_handle, void* (*task)(void*)) {
#ifdef _WIN32
HANDLE thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)task, NULL, 0, NULL);
if (thread == NULL) {
fprintf(stderr, "Failed to create thread\n");
}
*thread_handle = thread;
#else
pthread_t thread;
if (pthread_create(&thread, NULL, task, NULL) != 0) {
fprintf(stderr, "Failed to create thread\n");
}
pthread_detach(thread);
*thread_handle = (void*)thread;
#endif
}
#ifdef _WIN32
void kill_thread(void* thread_handle) {
HANDLE thread = (HANDLE)thread_handle;
TerminateThread(thread, 0);
}
#else
void kill_thread(void* thread_handle) {
pthread_t thread = (pthread_t)thread_handle;
pthread_cancel(thread);
}
#endif

13
libs/time.h Normal file
View File

@ -0,0 +1,13 @@
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
void wait(int time) {
#ifdef _WIN32
Sleep(time*1000);
#else
sleep(time);
#endif
}