如果我直接实现程序(不引入其他线程),它大约需要2个小时才能完成任务。使用多线程程序,即使只生成一个线程,也需要大约12个小时才能完成相同的任务(已经测试过)。
我尝试了几件事情,包括pthread_setaffinity_np将线程设置为单个CPU(在我使用的服务器上有24个可用的CPU),以及pthread_setschedparam设置调度策略(我只尝试了SCHED_BATCH)。但是,这些的效果迄今为止都微不足道。
有没有一般性的原因导致这种问题?
编辑:我已经添加了一些示例代码,这是我正在使用的,希望是最相关的部分。函数 process_job() 实际上是执行计算工作的函数,但将其包含在此处太多了。基本上,它读取两个数据文件,并使用这些文件对一个内存图形数据库执行查询,其中结果在几小时内写入两个大文件。
编辑第二部分:仅澄清,问题不在于我想使用线程来提高算法的性能。而是,我想同时运行我的算法的许多实例。因此,我预计当将算法放在一个线程中时,它将以类似于完全不使用多线程时的速度运行。
编辑第三部分:感谢所有的建议。目前我正在进行一些单元测试(查看哪些部分正在减速),如一些人建议的那样。由于程序加载和执行需要一段时间,所以检查测试结果需要时间,因此对于延迟的回复我深表歉意。我认为我想要澄清的主要观点是使线程可能导致程序运行缓慢的原因。从评论中了解到的情况是,它根本不应该这样。如果我能找到一个合理的解决方案,我会发帖的,再次感谢。
(最终)编辑部分4:事实证明,问题与线程无关。在这一点上描述它将会太过繁琐(包括使用编译器优化级别),但是这里发布的想法非常有用且受到赞赏。
struct sched_param sched_param = {
sched_get_priority_min(SCHED_BATCH)
};
int set_thread_to_core(const long tid, const int &core_id) {
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(core_id, &mask);
return pthread_setaffinity_np(tid, sizeof(mask), &mask);
}
void *worker_thread(void *arg) {
job_data *temp = (job_data *)arg; // get the information for the task passed in
...
long tid = pthread_self();
int set_thread = set_thread_to_core(tid, slot_id); // assume slot_id is 1 (it is in the test case I run)
sched_get_priority_min(SCHED_BATCH);
pthread_setschedparam(tid, SCHED_BATCH, &sched_param);
int success = process_job(...); // this is where all the work actually happens
pthread_exit(NULL);
}
int main(int argc, char* argv[]) {
...
pthread_t temp;
pthread_create(&temp, NULL, worker_thread, (void *) &jobs[i]); // jobs is a vector of a class type containing information for the task
...
return 0;
}