pthread_mutex_lock EINVAL hangs X on exit of multithreaded program (346.72)

My program (which is a trimmed down version of the real code which first exhibited the issue) has two threads, main thread creates two contexts (the second one shared from the first), the second is made current in the second thread. The second thread performs calculations with compute shaders, transferring the results to a texture which is displayed by the main thread.

When the program exits X becomes unresponsive, running htop via ssh shows kernel RT threads migration/0 through migration/3 using lots of CPU time. Killing -9 the program via ssh makes X respond again.

Running the program with valgrind --tool=helgrind reports arrors in libGL (and seems to avoid the X hang). Here’s the first error from the output:

==21507== Thread #1's call to pthread_mutex_lock failed
==21507==    with error code 22 (EINVAL: Invalid argument)
==21507==    at 0x4C305A1: pthread_mutex_lock (hg_intercepts.c:596)
==21507==    by 0x4EF338F: ??? (in /usr/lib/x86_64-linux-gnu/libGL.so.346.72)
==21507==    by 0x4EF56C2: ??? (in /usr/lib/x86_64-linux-gnu/libGL.so.346.72)
==21507==    by 0x4EF5839: ??? (in /usr/lib/x86_64-linux-gnu/libGL.so.346.72)
==21507==    by 0x4ECF8A4: ??? (in /usr/lib/x86_64-linux-gnu/libGL.so.346.72)
==21507==    by 0x400F027: _dl_fini (dl-fini.c:257)
==21507==    by 0x729DBC8: __run_exit_handlers (exit.c:82)
==21507==    by 0x729DC14: exit (exit.c:104)
==21507==    by 0x7287B4B: (below main) (libc-start.c:321)

I put the program (including the versions of GLFW and GLEW used, and some debug logs etc) here:
http://code.mathr.co.uk/nv-pthread-crash

git clone http://code.mathr.co.uk/nv-pthread-crash.git

(Hopefully the next page after creating this topic will allow me to attach the code and the all-important nvidia bug report log too.)
nvidia-bug-report.log.gz (202 KB)
nv-pthread-crash.tar.gz (1.56 MB)