【发布时间】:2014-04-19 16:45:04
【问题描述】:
这是我的第一个问题,因此请原谅我违反了您的政策。我希望每个线程有一个全局随机数引擎,为此我设计了以下方案:我启动的每个线程都从原子全局 int 获取唯一索引。有一个随机引擎的静态向量,其第 i 个成员被认为由索引为 i 的线程使用。如果索引大于向量大小的元素以同步方式添加到它。为了防止性能损失,我检查了两次索引是否大于向量大小:一次以非同步方式,另一次在锁定互斥锁后。到目前为止一切顺利,但以下示例因各种错误(堆损坏、malloc 错误等)而失败。
#include<vector>
#include<thread>
#include<mutex>
#include<atomic>
#include<random>
#include<iostream>
using std::cout;
std::atomic_uint INDEX_GEN{};
std::vector<std::mt19937> RNDS{};
float f = 0.0f;
std::mutex m{};
class TestAThread {
public:
TestAThread() :thread(nullptr){
cout << "Calling constructor TestAThread\n";
thread = new std::thread(&TestAThread::run, this);
}
TestAThread(TestAThread&& source) : thread(source.thread){
source.thread = nullptr;
cout << "Calling move constructor TestAThread. My ptr is " << thread << ". Source ptr is" << source.thread << "\n";
}
TestAThread(const TestAThread& source) = delete;
~TestAThread() {
cout << "Calling destructor TestAThread. Pointer is " << thread << "\n";
if (thread != nullptr){
cout << "Deleting thread pointer\n";
thread->join();
delete thread;
thread = nullptr;
}
}
void run(){
int index = INDEX_GEN.fetch_add(1);
std::uniform_real_distribution<float> uniformRnd{ 0.0f, 1.0f };
while (true){
if (index >= RNDS.size()){
m.lock();
// add randoms in a synchronized manner.
while (index >= RNDS.size()){
cout << "index is " << index << ", size is " << RNDS.size() << std::endl;
RNDS.emplace_back();
}
m.unlock();
}
f += uniformRnd(RNDS[index]);
}
}
std::thread* thread;
};
int main(int argc, char* argv[]){
std::vector<TestAThread> threads;
for (int i = 0; i < 10; ++i){
threads.emplace_back();
}
cout << f;
}
我做错了什么?!
【问题讨论】:
-
对我来说(GCC 4.8.1)你的代码可以工作。
-
顺便说一句,
m.lock(); RNDS.resize(index+1); m.unlock();应该可以正常工作。
标签: c++ multithreading random