什么功能对应于“同步”?在Java中?
Java中的synchronized
可以保证访问共享对象时的线程安全。
那么 C++ 呢?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
Java中的synchronized
可以保证访问共享对象时的线程安全。
那么 C++ 呢?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(5)
在 C++ 中,我实现了一个宏,让您只需执行以下操作即可同步对函数或方法的访问:
宏的定义方式如下:
这对我来说适用于所有三种流行的编译器 { Windows、Clang、GCC } 。该宏为该函数创建一个唯一的静态互斥变量,并立即将其锁定在该函数的范围内。它也可以在任何范围内使用,而不仅仅是函数范围。
您可以尝试这个测试程序来证明它是有效的:
当您运行这个程序时,您会得到以下输出——证明每个访问线程对函数的访问都是序列化的。您会注意到从进入函数到退出函数(两次)都有一秒的延迟。因为该函数现在已序列化,所以测试程序大约需要 2 秒才能完成该函数:
如果注释掉“synchronized;”语句,那么您将看到两个线程几乎同时进入该函数,产生类似于以下输出的内容,或者您可能会看到文本踩在其自身之上。因为我们不再同步,所以测试程序将花费大约 1 秒而不是 2 秒来完成:
In C++, I've implemented a macro that lets you simply do the following in order to synchronize access to a function or method:
Here's how the macro is defined:
This works for me with all three popular compilers { Windows, Clang, GCC }. This macro creates a unique static mutex variable for the function, and immediately locks it within the scope of that function. It could also be used within any scope, not just a function scope.
You can try this test program to prove that it works:
When you run this program, you get the following output -- demonstrating that access to the function is serialized for each accessing thread. You will notice the one-second delay from when the function is entered and when the function has exited (both times). Because the function is now serialized, the test program will take approximately 2 seconds for this function to complete:
If you comment out the "synchronized;" statement, then you'll see that both threads enter the function almost simultaneously, producing something similar to the following output, or you may see text that stomps on top of itself. Because we are no longer synchronized, the test program will take approximately 1 second to complete instead of 2 seconds:
在 C++ 中使用以下内容:
Use the following in C++:
尽管这个问题已经得到解答,但通过 这篇文章我仅使用标准库 (C++11) 对象制作了我的
synchronized
关键字版本:您可以像这样测试它:
这只是一个近似值Java 的
synchonized
关键字,但它有效。如果没有它,上一个示例的sayHello
方法可以按照 接受的答案 来实现:Despite this question has been already answered, by the idea of this article I made my version of
synchronized
keyword using just standard library (C++11) objects:You can test it like:
This is just an approximation of
synchonized
keyword of Java but it works. Without it thesayHello
method of the previous example can be implemented as the accepted answer says:C++03 中没有与 Java 中的
synchronized
等效的关键字。但是可以使用Mutex来保证线程的安全。There is no keyword in C++03 equivalent to
synchronized
in Java . But you can use Mutex to guarantee safety of thread.C++ 还没有内置线程或同步,您必须为此使用库。
Boost.Thread
是一个良好的可移植库,旨在与 C++0x 中建议的线程设施兼容 。C++ does not have built-in threading or synchronization (yet), you have to use libraries for that.
Boost.Thread
is a good portable library that is designed to be compatible with the proposed threading facilities in C++0x.