pthread_rwlock使用错误
写锁之后读锁竟然没有阻塞, 顺利运行下去了.
据常理,写锁之后,试图读加锁时会阻塞.
代码如:
pthread_rwlock_t rwl;
cout << "init: " << pthread_rwlock_init(&rwl, NULL) << endl;
cout << "wrlock: " << pthread_rwlock_wrlock(&rwl) << endl;
cout << "rdlock: " << pthread_rwlock_rdlock(&rwl) << endl;
cout << "unlock: " << pthread_rwlock_unlock(&rwl) << endl;
cout << "unlock: " << pthread_rwlock_unlock(&rwl) << endl;
cout << "wrlock: " << pthread_rwlock_wrlock(&rwl) << endl; // DEAD!
cout << "unlock: " << pthread_rwlock_unlock(&rwl) << endl;
输出为:
init: 0
wrlock: 0
rdlock: 35
unlock: 0
unlock: 0
程序会死锁在接下来的写锁定上. 35错误号为EDEADLK, 意为出现死锁.
仔细研究pthread读写锁的文档, 才发现原来如果一个线程写锁定后,
又调用pthread_rwlock_rdlock函数来读锁定,结果将无法预测。
Results are undefined if the calling thread currently owns a write lock on rwlock.
但是pthread_rwlock_rdlock()的man文档却对此没有明确指出.
参考:
读写锁 ( http://www.duangw.net/computer/history/pthread/rwlock.html )
pthread_rwlock_rdlock(3T) ( http://docs.hp.com/en/B2355-60103/pthread_rwlock_rdlock.3T.html )
不管怎样, pthread_rwlock_rdlock()都应该判断返回值,
因为有可能同时读太多会返回EAGAIN.
这样pthread_rwlock使用起来就麻烦许多.
查看了boost::thread, 它好像就没用pthread的读写锁.
(转载请注明来源于金庆的专栏)