C++0x 和静态局部变量的性能损失?
由于在 C++0x 中所有其他线程都应 在这样的情况下等待:
string& program_name() {
static string instance = "Parallel Pi";
return instance;
}
让我们假设最佳场景:程序员非常小心,即使有 100 个线程,也只有主线程调用函数program_name
,所有其他 99 个工作线程都忙于做有用的事情,其中不涉及调用这个“关键”函数。
我引用新的 C++0x-Std § 6.7.(4) stmt.decl
...这样的对象在控件第一次通过其声明时被初始化...如果控件在初始化对象时同时进入声明,则并发执行将等待初始化完成...
什么是实际开销需要一个现实世界的编译器强加给我,以确保静态初始化按照标准的要求完成。
- 是否需要锁/互斥体?我认为它们很昂贵,即使不是真正需要的?
- 如果它们很昂贵,是否可以通过更便宜的机制来完成?
编辑:添加字符串
...
What is a realistic performance loss due to the fact that in C++0x all other threads shall
wait in a case like this:
string& program_name() {
static string instance = "Parallel Pi";
return instance;
}
Lets assume the optimal scenario: The programmer was very careful that even with 100 threads only the main thread calls the function program_name
, all the other 99 worker threads are busy doing useful stuff, which does not involve calling this "critical" function.
I quote from the new C++0x-Std § 6.7.(4) stmt.decl
...such an object is initialized the first time control passes through its declaration... If control enters the declaration concurrently while the object is being initialized, the concurrent execution shall wait for completion of the initialization...
What is a realistic overhead that a real-world compiler is needed to impose on me to ensure that that static initialization is done as required by the standard.
- Is a lock/mutex required? I assume they are expensive, even when not really needed?
- If they are expensive, will this be done by less expensive mechanisms?
edit: added string
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这是并发编程中合理且非常正常的事情。不管怎样,这个语句并没有说所有其他线程必须等待这个初始化。他们必须等待以防他们需要访问初始化对象。
可能是。互斥锁/锁实际上并不那么昂贵,只有当锁定的代码片段需要被许多甚至所有线程频繁访问时它们才昂贵。
还有另一种非基于锁的解决方案 AFAIK。
I think this is reasonable and very normal thing to do in concurrent programming. Anyway, this statement doesn't say that all other threads must wait for this initialization. They have to wait in case they need to access the initializing object.
Could be. Mutex / lock aren't that expensive actually, they're expensive only when the locked code fragment needs to be accessed frequently by many or even all threads.
There are also another non-lock based solutions AFAIK.
如果您确实关心锁的价格,您可以简单地在启动工作线程之前调用该函数,这将初始化静态。如果您在线程启动后调用它,则您或编译器必须安排某种锁定,因此没有真正的额外开销。
If you were really concerned about the price of the lock, you could simply call the function before you started your worker threads, which would initialise the static. If you call it after the threads start, either you or the compiler has got to arrange for locking of some sort, so there is no real extra overhead.