diff --git a/chp5_synchronize/cancel_threads_semaphore/.gitignore b/chp5_synchronize/cancel_threads_semaphore/.gitignore new file mode 100644 index 0000000..521eceb --- /dev/null +++ b/chp5_synchronize/cancel_threads_semaphore/.gitignore @@ -0,0 +1 @@ +cancel_threads \ No newline at end of file diff --git a/chp5_synchronize/cancel_threads_semaphore/Makefile b/chp5_synchronize/cancel_threads_semaphore/Makefile new file mode 100644 index 0000000..acdedb8 --- /dev/null +++ b/chp5_synchronize/cancel_threads_semaphore/Makefile @@ -0,0 +1,18 @@ +CC=gcc +CFLAGS=-o cancel_threads -Wall -lpthread -lrt +SRCS=main.c + +.DEFAULT_GOAL := build + +build: + $(CC) $(CFLAGS) -fsanitize=address -static-libasan $(SRCS) + +release: + $(CC) $(CFLAGS) $(SRCS) + +debug: + $(CC) $(CFLAGS) -fsanitize=address -static-libasan -ggdb $(SRCS) + gdb -q cancel_threads + +clean: + rm -f cancel_threads diff --git a/chp5_synchronize/cancel_threads_semaphore/main.c b/chp5_synchronize/cancel_threads_semaphore/main.c new file mode 100644 index 0000000..34c31ec --- /dev/null +++ b/chp5_synchronize/cancel_threads_semaphore/main.c @@ -0,0 +1,54 @@ +#include +#include +#include +#include +#include + +#define THREAD_COUNT 10 + +void *expensive_task(void *); + +sem_t semaphore; + +int main(void) { + + sem_init(&semaphore, 0, 0); + + pthread_attr_t attr; + if (pthread_attr_init(&attr) != 0) { + perror("Error"); + return EXIT_FAILURE; + } + + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + + int n[THREAD_COUNT]; + pthread_t threads[THREAD_COUNT]; + for (int i = 0; i < THREAD_COUNT; i++) { + n[i] = i; + printf("Create thread number %d\n", i); + pthread_create(&threads[i], &attr, expensive_task, (void *)&n[i]); + } + + printf("Waiting semaphore...\n"); + sem_wait(&semaphore); + printf("Unlock semaphore\n"); + + for (int i = 0; i < THREAD_COUNT; i++) { + printf("Cancel thread %d\n", i); + pthread_cancel(threads[i]); + } + + sem_destroy(&semaphore); + + return EXIT_SUCCESS; +} + +void *expensive_task(void *args) { + const int tid = *((int *)args); + printf("Thread %d are running...\n", tid); + sleep(rand() % 31); + printf("Thread %d terminated!!!\n", tid); + sem_post(&semaphore); + pthread_exit(0); +}