6

我尝试了一个实验,我构建了一个简单的生产者/消费者程序。它们在不同的线程中运行。生产者生成一些数据,消费者在另一个线程中获取它。我实现的消息传递延迟约为 100 纳秒。谁能告诉我这是否合理或者那里有明显更快的实现?

我没有使用锁......只是简单的内存计数器。我的实验在这里描述:

http://tradexoft.wordpress.com/2012/10/22/how-to-move-data-between-threads-in-100-nanoseconds/

基本上,消费者等待计数器增加,然后调用处理函数。所以真的没有多少代码。我仍然很惊讶它花了 100ns。

消费者看起来像这样:

 void operator()()
    {
      while (true)
      {
        while (w_cnt==r_cnt) {};
        auto rc=process_data(data);
        r_cnt++;
        if (!rc)
          break;
      }
    }

生产者在有可用数据时简单地增加 w_cnt。

有更快的方法吗?

4

2 回答 2

6

我想你的延迟是操作系统如何安排上下文切换的产物,而不是自旋锁本身,我怀疑你可以做很多事情。

但是,您可以使用环形缓冲区一次移动更多数据。如果一个线程写一个线程读,你可以实现一个没有锁的环形缓冲区。本质上,这将是相同的自旋锁方法(等待直到tailidx != headidx),但生产者可以在将多个值切换到消费者之前将多个值泵入缓冲区。这应该会改善您的整体延迟(但不是您的单值延迟)。

于 2012-10-22T22:39:13.530 回答
3

If your threads are executed on different cores, then the fastest way to "send message" from one thread to another is write barrier(sfence).

When you write to some memory location, you actually write to the processors write buffer, not to the main-memory location. Write buffer is periodically flushed to main memory by the processor. Also, write instruction can be delayed when instruction reordering occurs. When actual write to main memory occurs, cache coherency protocol comes into play and "informs" another processor about memory location update. After that, another processor invalidates cache line and another thread will be able to see your changes.

Store barrier force processor to flush write buffer and prohibit instruction reordering and your program will be able to send more messages per second.

于 2012-10-23T10:02:34.623 回答