Skip to content

Instantly share code, notes, and snippets.

@BohuTANG
Created June 10, 2014 14:56
Show Gist options
  • Save BohuTANG/9728a852ce33ccc4036b to your computer and use it in GitHub Desktop.
Save BohuTANG/9728a852ce33ccc4036b to your computer and use it in GitHub Desktop.
a case for helgrind
/*
* make:
* gcc -g posixtest.c -pthread -o posixtest
* run:
* valgrind --tool=helgrind ./posixtest
*/
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
pthread_rwlock_t lock1;
pthread_rwlock_t lock2;
pthread_rwlock_t lock3;
static void *dowork(void *x)
{
pthread_rwlock_t *lock = (pthread_rwlock_t*)x;
sleep(3);
pthread_rwlock_unlock(lock);
return NULL;
}
int main()
{
pthread_rwlock_init(&lock1, NULL);
pthread_rwlock_init(&lock2, NULL);
pthread_rwlock_init(&lock3, NULL);
// case#1: lock order
pthread_rwlock_wrlock(&lock1);
pthread_rwlock_wrlock(&lock2);
pthread_rwlock_wrlock(&lock3);
pthread_rwlock_unlock(&lock1);
pthread_rwlock_unlock(&lock2);
pthread_rwlock_unlock(&lock3);
// case#2: unlock2 in background thread, casused helgrind incorrect warning
pthread_rwlock_wrlock(&lock2);
pthread_t t1;
pthread_create(&t1, NULL, dowork, (void*)&lock2);
pthread_rwlock_wrlock(&lock1);
pthread_rwlock_unlock(&lock1);
pthread_join(t1, NULL);
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment