我在测试 pthread 读写锁时遇到了意外的结果。
以下是我的代码。
#include <iostream>
#include <thread>
#include <pthread.h>
//locks declaration
pthread_rwlock_t rwlock;
//shared resource
int numbers[20];
int size = 0;
void readFrom()
{
int rc;
rc = pthread_rwlock_rdlock(&rwlock);
for(int index = 0; index < size; index++) {
std::cout << numbers[index] << " ";
}
std::cout << std::endl;
rc = pthread_rwlock_unlock(&rwlock);
}
void writeTo(int index, int val)
{
int rc;
rc = pthread_rwlock_wrlock(&rwlock);
numbers[index] = val;
size++;
rc = pthread_rwlock_unlock(&rwlock);
}
int main(int argc, char **argv)
{
int rc=0;
std::cout << std::endl;
std::thread threads[25];
rc = pthread_rwlock_init(&rwlock, NULL);
for(int i=0; i<20; ++i) {
threads[i] = std::thread(writeTo, i, i);
if(i % 5 == 0) {
threads[20 + (i / 5)] = std::thread(readFrom);
}
}
for(int i=0; i<24; ++i) {
threads[i].join();
}
std::cout << "size is " << size << std::endl;
threads[24] = std::thread(readFrom);
threads[24].join();
std::cout << std::endl;
rc = pthread_rwlock_destroy(&rwlock);
return 0;
}
经过几次运行,我偶尔会发现有一些意想不到的事情。这是一个例子:
0 1 2 3 0
它是读取器线程的输出。基本上,它说数字的大小现在是 5。在这种情况下,我希望结果应该是 0 1 2 3 4。
顺便说一句,我试图实现加法互斥锁,这会引发意想不到的行为。
我对解决方案和根本原因都很感兴趣。谁能帮帮我?
提前感谢任何帮助。