Don*_*Lun 43 c++ java multithreading synchronization
synchronized在Java保证线程的安全性.怎么样C++?
谢谢!
ybu*_*ill 44
在C++ 11中使用以下内容:
mutex _mutex;
void f()
{
unique_lock<mutex> lock(_mutex);
// access your resource here.
}
Run Code Online (Sandbox Code Playgroud)
如果您还没有C++ 11编译器,请使用boost.
尽管这个问题已经被回答说,对的想法这个文章我做我的版本的synchronized只使用标准库(C++ 11)对象关键字:
#include <mutex>
#define synchronized(m) \
for(std::unique_lock<std::recursive_mutex> lk(m); lk; lk.unlock())
Run Code Online (Sandbox Code Playgroud)
你可以测试它:
#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;
}
Run Code Online (Sandbox Code Playgroud)
这只是synchonizedJava关键字的近似值,但它有效.没有它,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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21938 次 |
| 最近记录: |