[英]error: ‘shared_mutex’ is not a member of ‘std’ using ReaderLock = std::shared_lock<std::shared_mutex>;
[英]Can I change data with a std::shared_lock on a std::shared_mutex?
我有多个缓冲区与多个读取器/写入器线程共享,并且不同的写入器以不同的方式更改数据。
例如,Writer1 只是追加新数据,而 Writer2 扩展缓冲区大小(重新分配 memory 并移动数据)。
如果我用一个互斥锁来同步所有对数据的访问,性能可能不会更好,因为大多数读取器只需要读取一个缓冲区,而大多数写入器只需将一小段数据写入单个缓冲区。
如果我为每个缓冲区准备一个互斥锁,线程之间的锁定/解锁关系会更加复杂。
现在我想确认一件事:
如果写入者仅使用互斥锁上的 shared_lock 更改数据,其他人是否会在同一个互斥锁上看到带有 unique_lock/shared_lock 的脏数据?
我编写了一个实验程序如下,看起来没有错误,但我还是不敢在产品中使用它。
atomic_bool g_abShouldRun = true;
sem_t g_semDoIt1;
sem_t g_semDone1;
sem_t g_semDoIt2;
sem_t g_semDone2;
shared_mutex g_mutex;
int g_iX = 3, g_iY = 9, g_iR1 = 1, g_iR2 = 3;
void writer() {
std::srand( 8 );
while( g_abShouldRun ) {
sem_wait( &g_semDoIt1 );
while( rand() % 8 != 0 )
;
{
shared_lock<shared_mutex> lk( g_mutex );
g_iX *= 2;
g_iY *= 2;
}
sem_post( &g_semDone1 );
};
};
void reader() {
std::srand( 8 );
while( g_abShouldRun ) {
sem_wait( &g_semDoIt2 );
while( rand() % 8 != 0 )
;
{
unique_lock<shared_mutex> lk( g_mutex );
g_iR1 = g_iX;
g_iR2 = g_iY;
}
sem_post( &g_semDone2 );
};
};
int main( int argc, char** argv ) {
int iLasting = 10, iError = 0;
if( argc > 1 )
iLasting = atoi( argv[1] );
steady_clock::time_point tpEnd = steady_clock::now() + seconds( iLasting );
if( sem_init( &g_semDoIt1, 0, 0 ) || sem_init( &g_semDone2, 0, 0 ) ||
sem_init( &g_semDoIt2, 0, 0 ) || sem_init( &g_semDone2, 0, 0 ) ) {
cerr << "Failed to create semaphors." << endl;
return EXIT_FAILURE;
}
thread thd1( writer );
thread thd2( reader );
while( steady_clock::now() < tpEnd ) {
sem_post( &g_semDoIt1 );
sem_post( &g_semDoIt2 );
sem_wait( &g_semDone1 );
sem_wait( &g_semDone2 );
if( g_iR1 * 3 != g_iR2 )
++iError;
}
g_abShouldRun = false;
sem_post( &g_semDoIt1 );
sem_post( &g_semDoIt2 );
thd1.join();
thd2.join();
sem_destroy( &g_semDoIt1 );
sem_destroy( &g_semDoIt2 );
sem_destroy( &g_semDone1 );
sem_destroy( &g_semDone2 );
cout << "Error:" << iError << endl;
return EXIT_SUCCESS;
};
以下问题一目了然:
unique_lock
;shared_lock
;shared_mutex
s, function using unique_lock
, function using shared_lock
} 元组你将使用多个线程和多个缓冲区,你需要自己弄清楚 - 但它会在 1 和缓冲区的数量之间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.