Without looking at the code, I suggest trying GCC's -sanitize=thread option and/or valgrind's helgrind tool.