如何在自己的线程上运行时钟

时间:2015-06-05 22:12:39

标签: c++ multithreading c++11 chrono

我试图用C ++创建一个最终发送MIDI数据的步进音序器。我通过在自己的线程上设置一个时钟来计算自上一次节拍后的时间量,并且如果是下一次节拍的时间,则会将一段数据写入控制台。

然而,我发现无论我将BPM设置为什么,我都会以一个明显太慢的速度收到消息。我似乎无法弄清楚为什么这个帖子的时机是错误的,并且我对std::chrono库的工作方式并不十分熟悉也没有帮助。想法?

以下代码:

#include <thread>
#include <mutex>
#include <chrono>
#include <vector>
#include <iostream>

class StepSequencer {
 public:
  StepSequencer();
  ~StepSequencer();
  void run();
  void setBeatsPerMinute(float bpm);
  void addNote(int noteValue, int beatIndex);
  void playNote(int beatIndex);
 protected:
  int mNumberOfBeatBins;
  int mSequencerPlayhead;
  float mBeatsPerMinute;
  float mSecondsPerBeat;
  std::vector<int> mBeatBins;
  std::mutex mMutex;
  std::thread mSequencerThread;
  bool mRunSequencerThread;
  std::chrono::time_point<std::chrono::system_clock> mLastBeatTime;
  std::chrono::time_point<std::chrono::system_clock> mCurrentTime;
};

#include "stdafx.h"
#include "StepSequencer.h"

StepSequencer::StepSequencer() {
  mNumberOfBeatBins = 16;
  for(int i = 0; i < 16; i++) {
    mBeatBins.push_back(0);
  }

  mBeatsPerMinute = 0;
  mSecondsPerBeat = 1;

  mLastBeatTime = std::chrono::system_clock::now();
  mCurrentTime = std::chrono::system_clock::now();

  mSequencerPlayhead = 0;

    mRunSequencerThread = false;
    mSequencerThread = std::thread(&StepSequencer::run, this);
}

StepSequencer::~StepSequencer() {
  if(mSequencerThread.joinable()) {
    mSequencerThread.join();
  }
}

void StepSequencer::run() {
  mRunSequencerThread = true;
  while(mRunSequencerThread) {
        mCurrentTime = std::chrono::system_clock::now();
    mMutex.lock();
        if (std::chrono::duration_cast<std::chrono::seconds>(mCurrentTime - mLastBeatTime).count() > mSecondsPerBeat) {
      mSequencerPlayhead++;
      mSequencerPlayhead = mSequencerPlayhead % mNumberOfBeatBins;
      playNote(mSequencerPlayhead);
            mLastBeatTime = std::chrono::system_clock::now();
    }
    mMutex.unlock();
    this_thread::sleep_for(std::chrono::milliseconds(1));
  }
} 

void StepSequencer::setBeatsPerMinute(float bpm) {
  mMutex.lock();
  mBeatsPerMinute = bpm;
  if(mBeatsPerMinute > 0) {
      mSecondsPerBeat = 60.0 / mBeatsPerMinute;
  }
  else {
    mSecondsPerBeat = 1;
  }
 mMutex.unlock();
}

void StepSequencer::addNote(int noteValue, int beatIndex) {
  mBeatBins[beatIndex] = noteValue;
}

void StepSequencer::playNote(int beatIndex) {
  std::cout << mBeatBins[beatIndex] << std::endl;
}

1 个答案:

答案 0 :(得分:2)

std::chrono::seconds表示'至少35位的有符号整数类型'。所以你得到的值count()每秒只增加一次,每分钟可以选择60,30,20,15,12等。

以毫秒为单位工作或使用由浮点值支持的自定义持续时间。