C++ 线程间无过载的同步
对于如何在不同线程之间的公共资源上实现良好的互斥,我找不到一个好的解决方案 我有很多方法(来自一个类)可以访问数据库,这就是其中之一C++ 线程间无过载的同步,c++,multithreading,synchronization,raspberry-pi,mutex,C++,Multithreading,Synchronization,Raspberry Pi,Mutex,对于如何在不同线程之间的公共资源上实现良好的互斥,我找不到一个好的解决方案 我有很多方法(来自一个类)可以访问数据库,这就是其中之一 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(resu
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\u mutex\u t
init,锁定等待,解锁信号,在析构函数中销毁
像这样:
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\u mutex
函数的返回值:0表示成功,非零表示错误。不要“实现”您自己的信号量。改用操作系统服务。您不能自己实现“睡眠”,因为您的程序永远不能什么都不做。你需要与操作系统调度程序交互才能有效睡眠。你建议怎么做?你可以在构造函数中使用pthread\u mutex\t
init,锁定等待,解锁信号,在析构函数中销毁。或者看看这里:正是我说的。使用操作系统服务。我想你应该使用std::lock\u guard lock(我的互斥锁)
在C++11中,您可以使用std::mutex
,而OP似乎可以使用RAII,因此除了使用std::lock\u guard