无过载的线程间同步

Synchronization between threads without overload

本文关键字:同步 线程      更新时间:2023-10-16

关于如何在不同线程之间的公共资源上实现良好的互斥,我找不到一个好的解决方案。

我有很多方法(从一个类)做很多访问数据库,这是其中之一

string id = QUERYPHYSICAL + toString(ID);
wait();
mysql_query(connection, id.c_str());
MYSQL_RES *result = mysql_use_result(connection);
while (MYSQL_ROW row = mysql_fetch_row(result)){
    Physical[ID - 1].ID = atoi(row[0]);
    Physical[ID - 1].NAME = row[1];
    Physical[ID - 1].PEOPLE = atoi(row[2]);
    Physical[ID - 1].PIRSTATUS = atoi(row[3]);
    Physical[ID - 1].LIGHTSTATUS = atoi(row[4]);
}
mysql_free_result(result);
signal();

方法等待并发出信号做这些事情:

void Database::wait(void) {
    while(!this->semaphore);
    this->semaphore = false;
}
void Database::signal(void) {
    this->semaphore = true;
}

但是在这种情况下,我的CPU使用率超过190%(从/proc/loadavg读取)。我应该做些什么来减少CPU过载,让系统更高效?我在800MHz的RaspberryPi

可以在构造函数中使用pthread_mutex_t init,在等待时使用lock,在信号时使用unlock,在析构函数中使用destroy。

:

class Mutex{
  pthread_mutex_t m; 
public:
  Mutex(){
    pthread_mutex_init(&m,NULL); 
  }
  ~Mutex(){
    pthread_mutex_destroy(&m);  
  }
  void wait() {
    pthread_mutex_lock(&m);
  }
  void signal() {
    pthread_mutex_unlock(&m);
  }
} ;

您还应该检查pthread_mutex函数的返回值:0表示成功,非零表示错误。