数组上的多线程 [英] multithreading on arrays

查看:90
本文介绍了数组上的多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生产者和n个消费者。有一个大小为n的数组。生产者将东西放入数组中,只要元素可用,消费者就从数组中获取一个元素。如何实现这个目标?

我尝试循环检查每个元素的可用性并等待其相应的条件信号。但是这会导致死锁。

I''ve got one producer and n consumers. There''s an array of size n. The producer puts things into the array, and a consumer takes one element from the array whenever an element is available. How to achieve this?
I tried for loop to check the availability of every element and wait for its corresponding conditional signal. But this leads to deadlocks.

推荐答案

对于生产者 - 消费者模式,使用队列而不是数组要好得多: http://www.cplusplus.com/reference/queue/queue/ [ ^ ]。



如需使用队列,你需要进行排队/出队操作线程安全。你会发现这个问题上有足够多的材料你看这里:

http://bit.ly/11A3Liy [ ^ ]



-SA
For producer-consumer schema, it''s much better to use the queue, not an array: http://www.cplusplus.com/reference/queue/queue/[^].

For such use of the queue, you need to make your queuing/dequeuing operations thread-safe. You will find more than enough material on this problem is you look here:
http://bit.ly/11A3Liy[^]

—SA


在同步对象中包装您的读写函数,一次只有一个线程可以访问您的阵列。

Wrap your reading and writing functions in a synchronization object, then only one thread at a time can access your array.
class MyArrayWrapper  // untested code
{
   private:
      std::vector<int> MyArray;
      CCriticalSection MyCC;    // Sync Object

   public:
      int WriteToEnd(int Num)
      {
         CSingleLock cs(&MyCC); // Wait till MyCC is free
         MyArray.push_back(Num);
         return MyArray.size();
         // cs goes out of scope and releases MyCC so another thread can run
      }

      int ReadAndRemoveFromBack()
      {
         CSingleLock cs(&MyCC);
         int ret = MyArray.back();
         MyArray.pop_back();
         return ret;
      }
}


如果内存不是问题,你的制作人可以创建这个数组n次,所有这些都是自己的DATAS。因此不存在死锁。



另一种方式并不总是检查它是否可用。如果没有(我不知道你的算法)你可以做任何其他的工作,或者你可以睡觉,如果不可用再次增加睡眠时间再睡一觉。
If memory is not a problem your producer can create this array n times and all this n comsumer takes their own datas. So there will be no deadlocks.

Another way is not always check it is available. If not (I do not know you algorithm) you can do any other job or you can sleep and again if not available increase the sleep time and sleep again.


这篇关于数组上的多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆