[英]what is correspoding feature for synchronized in java?
Java
synchronized
可以保證線程的安全。 C++
呢?
謝謝!
在 C++ 中使用以下內容:
#include <mutex>
std::mutex _mutex;
void f()
{
std::unique_lock<std::mutex> lock(_mutex);
// access your resource here.
}
盡管這個問題已經被回答說,對的想法這個文章我做我的版本的synchronized
關鍵字只使用標准庫(C ++ 11)對象:
#include <mutex>
#define synchronized(m) \
for(std::unique_lock<std::recursive_mutex> lk(m); lk; lk.unlock())
您可以像這樣測試它:
#include <iostream>
#include <iomanip>
#include <mutex>
#include <thread>
#include <vector>
#define synchronized(m) \
for(std::unique_lock<std::recursive_mutex> lk(m); lk; lk.unlock())
class Test {
std::recursive_mutex m_mutex;
public:
void sayHello(int n) {
synchronized(m_mutex) {
std::cout << "Hello! My number is: ";
std::cout << std::setw(2) << n << std::endl;
}
}
};
int main() {
Test test;
std::vector<std::thread> threads;
std::cout << "Test started..." << std::endl;
for(int i = 0; i < 10; ++i)
threads.push_back(std::thread([i, &test]() {
for(int j = 0; j < 10; ++j) {
test.sayHello((i * 10) + j);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}));
for(auto& t : threads) t.join();
std::cout << "Test finished!" << std::endl;
return 0;
}
這只是 Java 的synchonized
關鍵字的近似值,但它有效。 沒有它,前面例子中的sayHello
方法可以按照接受的答案來實現:
void sayHello(unsigned int n) {
std::unique_lock<std::recursive_mutex> lk(m_mutex);
std::cout << "Hello! My number is: ";
std::cout << std::setw(2) << n << std::endl;
}
C++03 中沒有與 Java 中的synchronized
等效的關鍵字。 但是你可以使用互斥鎖來保證線程的安全。
C++ 沒有內置線程或同步(還),您必須為此使用庫。 Boost.Thread
是一個很好的可移植庫,旨在與C++0x 中提議的線程工具兼容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.