diff --git a/README.md b/README.md new file mode 100644 index 0000000..508c4ff --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +# What this repo is + +This repo has some examples using multi-threaded-programming because someone +asked about how it works. diff --git a/example01_singleThread_c_impl/.gitignore b/example01_singleThread_c_impl/.gitignore new file mode 100644 index 0000000..eb32573 --- /dev/null +++ b/example01_singleThread_c_impl/.gitignore @@ -0,0 +1,3 @@ +build*/ +compile_commands.json +.cache/ diff --git a/example01_singleThread_c_impl/CMakeLists.txt b/example01_singleThread_c_impl/CMakeLists.txt new file mode 100644 index 0000000..a4e3549 --- /dev/null +++ b/example01_singleThread_c_impl/CMakeLists.txt @@ -0,0 +1,19 @@ +cmake_minimum_required(VERSION 3.9) +project(Example01_SingleThread_C_IMPL) + +set(Example01_SOURCES + "${CMAKE_CURRENT_SOURCE_DIR}/src/main.c") + +set(CMAKE_C_FLAGS "-Wall -Wextra -Wpedantic") +set(CMAKE_C_FLAGS_DEBUG "-O0 -g") +set(CMAKE_C_FLAGS_RELEASE "-O3 -DNDEBUG") + +if(NOT CMAKE_BUILD_TYPE OR "${CMAKE_BUILD_TYPE}" MATCHES ^$) + set(CMAKE_BUILD_TYPE "Debug") + message("CMAKE_BUILD_TYPE is set to Debug by default") +endif() + +add_executable(Example01 + ${Example01_SOURCES}) + +target_link_libraries(Example01 PUBLIC pthread) diff --git a/example01_singleThread_c_impl/src/main.c b/example01_singleThread_c_impl/src/main.c new file mode 100644 index 0000000..4ebe266 --- /dev/null +++ b/example01_singleThread_c_impl/src/main.c @@ -0,0 +1,61 @@ +#include +#include +#include + +typedef struct ThreadData { + mtx_t mutex; + int lock_before_printing; +} ThreadData; + +int functionCalledByThread(void *user_data) { + ThreadData *data = (ThreadData*)user_data; + + if(data->lock_before_printing != 0) { + // lock before printing + mtx_lock(&data->mutex); + } + puts("Hello from spawned thread"); + if(data->lock_before_printing != 0) { + // unlock after printing + mtx_unlock(&data->mutex); + } + + return 0; +} + +int main(int argc, char **argv) { + // create the ThreadData that is shared with the thread + ThreadData td; + mtx_init(&td.mutex, mtx_plain); + td.lock_before_printing = 1; + + // check args + --argc; ++argv; + while(argc > 0) { + if(strcmp("-n", argv[0]) == 0 || strcmp("--no-lock", argv[0]) == 0) { + td.lock_before_printing = 0; + puts("Disabling use of mutex before printing"); + } + --argc; ++argv; + } + + // create the thread + thrd_t thread_handle; + thrd_create(&thread_handle, functionCalledByThread, &td); + + if(td.lock_before_printing != 0) { + // lock before printing + mtx_lock(&td.mutex); + } + puts("Hello from main thread"); + if(td.lock_before_printing != 0) { + // unlock after printing + mtx_unlock(&td.mutex); + } + + thrd_join(thread_handle, NULL); + + // cleanup + mtx_destroy(&td.mutex); + return 0; +}