diff --git a/examples/.gitignore b/examples/.gitignore new file mode 100644 index 0000000..76e1fda --- /dev/null +++ b/examples/.gitignore @@ -0,0 +1,2 @@ +a.out +a.exe diff --git a/examples/comp_run_lin.sh b/examples/comp_run_lin.sh new file mode 100755 index 0000000..189e981 --- /dev/null +++ b/examples/comp_run_lin.sh @@ -0,0 +1,11 @@ +echo -n "File: " +read file + +while true +do +clear && gcc $file && ./a.out +echo "----------------" +echo "Programm ended." +echo "----------------" +read _ +done diff --git a/examples/comp_run_win.sh b/examples/comp_run_win.sh new file mode 100755 index 0000000..57fc2d4 --- /dev/null +++ b/examples/comp_run_win.sh @@ -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 diff --git a/examples/threads.c b/examples/threads.c new file mode 100644 index 0000000..72045d6 --- /dev/null +++ b/examples/threads.c @@ -0,0 +1,26 @@ +#include +#include + +#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; +} diff --git a/examples/wait.c b/examples/wait.c new file mode 100644 index 0000000..531489a --- /dev/null +++ b/examples/wait.c @@ -0,0 +1,10 @@ +#include + +#include "../libs/time.h" + +int main() { + printf("Wait 5 seconds...\n"); + wait(5); + + return 0; +} diff --git a/libs/threads.h b/libs/threads.h new file mode 100644 index 0000000..f6d69f7 --- /dev/null +++ b/libs/threads.h @@ -0,0 +1,38 @@ +#ifdef _WIN32 +#include +#else +#include +#include +#endif + +#include +#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 diff --git a/libs/time.h b/libs/time.h new file mode 100644 index 0000000..8e69640 --- /dev/null +++ b/libs/time.h @@ -0,0 +1,13 @@ +#ifdef _WIN32 +#include +#else +#include +#endif + +void wait(int time) { +#ifdef _WIN32 + Sleep(time*1000); +#else + sleep(time); +#endif +}