在用c ++线程/升压线程有效的方法 [英] efficient approach in using c++ thread/ boost thread

查看:122
本文介绍了在用c ++线程/升压线程有效的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个伪code,需要并行化:

I have a pseudo code that requires parallelization:

int thread_count=8;
for(int i=1;i<100000;i++)
{
do_work(i,record);
}

do_work功能将运行基于我写输出记录。现在,我想这个序列化的实现转换成多线程执行;

do_work function will work based on i and write outputs to record. Now, I would like to convert this serialized implementation into a multithreading implementation;

我知道我可以做类似

int thread_count=8;
for(int i=1;i<100000;i++)
{
boost::thread t1(do_work,i,std::ref(record));
}

但是,这将创造数千个线程,这将影响性能的。我相信张贴的问题,应该是需要multi_threading最自然的形式,我想知道什么是标准C ++的做法来解决这个问题...谢谢你。

But this will create thousands of threads which will harm performance. I believe the problem posted should be the most natural form that requires multi_threading and I would like to know what is the standard c++ practice to solve this problem... Thank you.

推荐答案

创建多线程性能有所帮助,最多只有你有,因为每个线程都可以在自己的核心运行,并不会影响其他内核的数量。然而,你说,他们 do_work()函数写入记录。如果变量在线程之间使用互斥在这种情况下会降低可怕,即使你对自己的内核运行的线程性能共享。

Creating multiple threads helps performance only up to the number of cores you have since each thread can run in its own core and not affect the other. However you said they do_work() function writes to a record. If that variable is shared between the threads using a mutex in this case will horribly degrade performance even if you are running threads on their own cores.

一个自旋锁可以减少在这种情况下,一个互斥体的时间开销帮助,但它仍是基于的std :: atomic_flag (至少提高::自旋锁是GNU G ++),这是一个原子变量,因此将需要同步高速缓存的开销,在编译时。您应该只放眼并行这份长达其中每个线程都可以在一个独立的内核上运行的程度。

A spinlock can help in reducing the time overhead of a mutex in this case but it is still based on std::atomic_flag (at least boost::spinlock is when compiled on GNU g++) which is an atomic variable and will thus require the overhead of syncing caches. You should only look to parallelize this up to the extent where each thread can run in an independent core.

除非你的程序是一样,你需要请求,而不会阻塞其他的服务器。在这种情况下的线程池(也许它的增长和动态收缩)应该是正确的选择。如Apache服务器也使用线程池在很多情况下

Unless your program is like a server where you need to serve requests without blocking others. In which case a pool of threads (maybe which grows and shrinks dynamically) should be the right option. Servers like Apache also use thread pools in many cases

这篇关于在用c ++线程/升压线程有效的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆