gpt4 book ai didi

c - 如何使用 pthreads 读/写共享变量?

转载 作者:太空狗 更新时间:2023-10-29 16:05:03 25 4
gpt4 key购买 nike

我有两个线程,在 Linux 上使用 C pthreads。其中一个写入数据,另一个读取数据。我正在使用一个变量来允许读取线程何时被允许读取和写入线程何时被允许。所以互斥量适用于这个名为“newData”的 bool 变量。我的问题是:我是否需要在“if”条件内的访问周围锁定/解锁互斥体?这两种方法都有效,但我认为只是因为在 this 变量上重叠写/读的机会很少。我展示了两种选择以更好地解释我的问题:

线程 1:

pthread_mutex_lock( &lattice_mutex );
if (!newData) {
pthread_mutex_unlock( &lattice_mutex );
uchar *lattice_pos = lattice;
int i;
for(i=0; i<size; i++) {
*lattice_pos = rand()%CHAR_MAX;
lattice_pos++;
}
pthread_mutex_lock( &lattice_mutex );
newData = TRUE;
pthread_mutex_unlock( &lattice_mutex );
} else {
pthread_mutex_unlock( &lattice_mutex );
}

线程 2:

pthread_mutex_lock( &lattice_mutex );
if(newData) {
pthread_mutex_unlock( &lattice_mutex );
renderUpdate();
pthread_mutex_lock( &lattice_mutex );
newData = FALSE;
pthread_mutex_unlock( &lattice_mutex );
} else {
pthread_mutex_unlock( &lattice_mutex );
}

第二个版本,有效但我不知道它是否正确:

线程 1:

if (!newData) {
uchar *lattice_pos = lattice;
int i;
for(i=0; i<size; i++) {
*lattice_pos = rand()%CHAR_MAX;
lattice_pos++;
}
pthread_mutex_lock( &lattice_mutex );
newData = TRUE;
pthread_mutex_unlock( &lattice_mutex );
}

线程 2:

if(newData) {
renderUpdate();
pthread_mutex_lock( &lattice_mutex );
newData = FALSE;
pthread_mutex_unlock( &lattice_mutex );
}

最佳答案

这是从您的第一个版本派生而来的 - 它稍微简单一些。

线程 1:作家

pthread_mutex_lock(&lattice_mutex);
if (!newData) {
pthread_mutex_unlock(&lattice_mutex); // Omit?
uchar *lattice_pos = lattice;
int i;
for (i = 0; i < size; i++)
*lattice_pos++ = rand() % CHAR_MAX;
pthread_mutex_lock(&lattice_mutex); // Omit?
newData = TRUE;
}
pthread_mutex_unlock(&lattice_mutex);

线程 2:读者

pthread_mutex_lock(&lattice_mutex);
if (newData) {
pthread_mutex_unlock(&lattice_mutex); // Omit?
renderUpdate();
pthread_mutex_lock(&lattice_mutex); // Omit?
newData = FALSE;
}
pthread_mutex_unlock(&lattice_mutex);

这完全取决于晶格信息的使用方式,但考虑到互斥量的名称,我认为您在修改晶格时应该将其锁定,因此两对线标记为“省略?”应该被删除。否则,晶格不会受到并发访问的保护。

补充:我认为第二个版本是错误的——它没有正确保护格子。

关于c - 如何使用 pthreads 读/写共享变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/607374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com