我有两个线程,在 linux上使用C pthreads.其中一个写入数据,另一个正在读取数据.我正在使用一个变量来允许读取线程,当允许读取时,写入一个是允许的.因此,互斥锁适用于这个名为“newDat
线程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);
它取决于格子信息的确切使用方式,但考虑到互斥体的名称,我认为你应该在修改晶格时保持锁定,因此标记为“忽略”的两对线条?应该删除.否则,不保护晶格不受并发访问的影响.
补充:我认为第二个版本是错误的 – 它没有正确保护晶格.