我有一个线程可以无限循环地计算数据。 它产生三个结果
- 一个std :: vector(在每个vector元素后面都有一个float
- 堆上的3个元素组成的数组)
- 一个int数组*
- 一个指示int []大小的int。
现在,另外两个线程应该处理此数据(也无穷)。由于这三个线程的处理时间不同,因此有时会“跳过”数据。
std::vector<float*> a_vecor;
int* a_Array;
int a_Array_size;
std::mutex a_mutex;
void thread_A()
{
while (true)
{
calculate();
a_mutex.lock();
a_vector = getvector();
a_Array = getArray();
a_Array_size = getArraysize();
a_mutex.unlock();
}
}
void thread_B()
{
while (true)
{
a_mutex.lock();
std::vector<float*> b_vector = a_vector;
int* b_Array = a_Array;
int b_array_Size = a_array_Size;
a_mutex.unlock();
calculate_b();
}
}
void thread_C()
{
while (true)
{
a_mutex.lock();
std::vector<float*> c_vector = a_vector;
int* c_Array = a_Array;
int c_array_Size = a_array_Size;
a_mutex.unlock();
calculate_c();
}
}
我的问题是如何将这些数据从一个线程传递到另一个线程? 我实际上将在以下线程中复制这三个参数,但我可以:
std::vector <float*> b = calculate();
std::vector <float*> a = b;
这是副本还是参考?仅作为参考的矢量元素怎么样? 复制向量和数组的最快方法是什么?循环也不会在内部运行吗? 信息流只是一个方向,一个过程生成数据,下一过程仅读取它。我可以利用这个吗? 互斥有替代品吗?
Define your data in the main function and then pass them to the threads using
std::ref()
, then threads the will deal with the data itself not a copy.And of course you have to use
std::mutex
s andstd::shared_mutex
s因此,您希望一个线程写入数据而另一个线程读取数据吗? -实现此目的的标准方法是使用互斥锁。实际上,您确实需要一个互斥锁,因为即使您尝试访问它,所读取的值(即向量的大小)也可能会发生变化-导致未定义的行为(可能是段错误!)。
同样,对于vector,一旦向其添加更多元素,就不能保证它位于同一位置-可能是需要更多的内存并将其移动到其他位置! -如果您正在阅读,这是不好的。
So I really don't see what choice you have - unless you make a copy - but that is more wasteful. If your vector is fixed size you might be able to get away with using a vector of
std::atomic<int/float>
, but then if your vector is not changing in size then use a std::array.您可以使用双端队列(双端队列-有效地是一个链表),其中每个元素确实留在内存中的相同位置,并且可以安全地从假定您的编写者没有从双端队列中删除项目的方式读取!
因此,我将从互斥量开始-它非常易于使用,并提供一些共享数据,例如: