Why do pthreads’ condition variable functions require a mutex?

It’s just the way that condition variables are (or were originally) implemented. The mutex is used to protect the condition variable itself. That’s why you need it locked before you do a wait. The wait will “atomically” unlock the mutex, allowing others access to the condition variable (for signalling). Then when the condition variable is … Read more

cmake and libpthread

@Manuel was part way there. You can add the compiler option as well, like this: If you have CMake 3.1.0+, this becomes even easier: set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) target_link_libraries(my_app PRIVATE Threads::Threads) If you are using CMake 2.8.12+, you can simplify this to: find_package(Threads REQUIRED) if(THREADS_HAVE_PTHREAD_ARG) target_compile_options(my_app PUBLIC “-pthread”) endif() if(CMAKE_THREAD_LIBS_INIT) target_link_libraries(my_app “${CMAKE_THREAD_LIBS_INIT}”) endif() Older CMake … Read more

Significance of -pthread flag when compiling

Try: gcc -dumpspecs | grep pthread and look for anything that starts with %{pthread:. On my computer, this causes files to be compiled with -D_REENTRANT, and linked with -lpthread. On other platforms, this could differ. Use -pthread for most portability. Using _REENTRANT, on GNU libc, changes the way some libc headers work. As a specific … Read more

Still Reachable Leak detected by Valgrind

There is more than one way to define “memory leak”. In particular, there are two primary definitions of “memory leak” that are in common usage among programmers. The first commonly used definition of “memory leak” is, “Memory was allocated and was not subsequently freed before the program terminated.” However, many programmers (rightly) argue that certain … Read more

pthread function from a class

You can’t do it the way you’ve written it because C++ class member functions have a hidden this parameter passed in. pthread_create() has no idea what value of this to use, so if you try to get around the compiler by casting the method to a function pointer of the appropriate type, you’ll get a … Read more

Pthreads in C. Simple example doesn’t work [closed]

This line printf(“(%s)”,’Hi. It’s thread number 1′); should be printf(“(%s)”, “Hi. It’s thread number 1”); String literals are enclosed using quotation marks “. Also passing 1 to pthread_join() as 2nd parameter most likley invokes undefined behaviour, as it tells the function to write a value of type void * to address 1, which is not … Read more