无过载的线程间同步
Synchronization between threads without overload
关于如何在不同线程之间的公共资源上实现良好的互斥,我找不到一个好的解决方案。
我有很多方法(从一个类)做很多访问数据库,这是其中之一
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表示成功,非零表示错误。
相关文章:
- 在C++中同步线程
- 将 10 个线程与原子布尔值同步
- 线程过程中的线程同步问题
- 如何定期同步线程?
- 同步线程安全的API,用于暴露缓存数据
- 如何在 pthreads 中正确同步线程
- 通过shared_ptr同步:线程清理器误报
- 如何同步线程以捕获相同数量的帧
- 同步线程和信号
- 使用条件变量(监视器)同步线程
- 同步线程创建和销毁(静态)对象
- NVIDA的CUDA"__syncthreads()"在传统C++中的等价物是什么。如何专业地同步线程?
- 使用事件同步线程
- 如何同步线程(消费者/生产者)
- 以最优雅的方式同步线程
- 使用互斥锁同步线程
- 计算着色器-如何全局同步线程
- GPU for loops:避免扭曲发散和隐式同步线程
- 如果已知访问顺序是安全的,如何在没有互斥锁的情况下同步线程/CPU
- Qt - 同步线程不起作用 - 线程停止但实际上不会停止,有时在不应该停止的时候停止