我正在为一个游戏提供概念证明测试程序,其中某些操作被线程化并且信息输出到每个线程的命令窗口。到目前为止,我已经获得了基本的线程处理工作,但似乎我的被调用函数中的couting并不是针对每个线程编写的,而是每个线程都覆盖其他输出。使用线程时的意外输出
期望或预期的输出是每个线程将输出mLaser的mCycle函数内的信息。本质上,这意味着每个对象都需要排序计时器,直到该对象完成任务为止。每个线程应该有一个输出,所以如果有五个线程在运行,那么应该有五个计数器独立计数。
当前输出是这样的:每个线程都在同一个空间输出自己的信息,然后覆盖另一个线程试图输出的内容。
下面是程序的当前输出的一个示例:
时间直到周期时间直到周期74完成:36完成:
92秒2秒按下光任意键继续。 。 。
如果您检查信息是如何从mCycle中传输的,您可以看到数字和其他文本位于不应该出现的位置的像差。
什么应显示更长时间这些行:
时间直到周期1结束:
92秒
时间直到周期2结束:
112秒
直到第3周期完成的时间:
34秒
周期4已完成!
我不确定这是由于某种线程锁定是由于我的代码是如何构造的,或者仅仅是我在输出编码中的疏忽而导致的。如果我能得到一双新的眼睛来查看代码,并指出任何可能是错误的东西,我将不胜感激。
这里是我的代码,它应该是编译的任何MSVS 2013安装
#include <iostream>
#include <Windows.h>
#include <string>
#include <vector>
#include <random>
#include <thread>
#include <future>
using namespace std;
class mLaser
{
public:
mLaser(int clen, float mamt)
{
mlCLen = clen;
mlMAmt = mamt;
}
int getCLen()
{
return mlCLen;
}
float getMAmt()
{
return mlMAmt;
}
void mCycle(int i1, int mCLength)
{
bool bMCycle = true;
int mCTime_left = mCLength * 1000;
int mCTime_start = GetTickCount(); //Get cycle start time
int mCTime_old = ((mCTime_start + 500)/1000);
cout << "Time until cycle " << i1 << " is complete: " << endl;
while (bMCycle)
{
cout << ((mCTime_left + 500)/1000) << " seconds";
bool bNChange = true;
while (bNChange)
{
//cout << ".";
int mCTime_new = GetTickCount();
if (mCTime_old != ((mCTime_new + 500)/1000))
{
//cout << mCTime_old << " " << ((mCTime_new+500)/1000) << endl;
mCTime_old = ((mCTime_new + 500)/1000);
mCTime_left -= 1000;
bNChange = false;
}
}
cout << " \r" << flush;
if (mCTime_left == 0)
{
bMCycle = false;
}
}
cout << "Mining Cycle " << i1 << " finished" << endl;
system("Pause");
return true;
}
private:
int mlCLen;
float mlMAmt;
};
string sMCycle(mLaser ml, int i1, thread& thread);
int main()
{
vector<mLaser> mlasers;
vector<thread> mthreads;
future<string> futr;
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> laser(1, 3);
uniform_int_distribution<> cLRand(30, 90);
uniform_real_distribution<float> mARand(34.0f, 154.3f);
int lasers;
int cycle_time;
float mining_amount;
lasers = laser(gen);
for (int i = 0; i < lasers-1; i++)
{
mlasers.push_back(mLaser(cLRand(gen), mARand(gen)));
mthreads.push_back(thread());
}
for (int i = 0; i < mlasers.size(); i++)
{
futr = async(launch::async, [mlasers, i, &mthreads]{return sMCycle(mlasers.at(i), i + 1, mthreads.at(i)); });
//mthreads.at(i) = thread(bind(&mLaser::mCycle, ref(mlasers.at(i)), mlasers.at(i).getCLen(), mlasers.at(i).getMAmt()));
}
for (int i = 0; i < mthreads.size(); i++)
{
//mthreads.at(i).join();
}
//string temp = futr.get();
//float out = strtof(temp.c_str(),NULL);
//cout << out << endl;
system("Pause");
return 0;
}
string sMCycle(mLaser ml, int i1, thread& t1)
{
t1 = thread(bind(&mLaser::mCycle, ref(ml), ml.getCLen(), ml.getMAmt()));
//t1.join();
return "122.0";
}
感谢您的建议,Mutexs是我可以修复的名单上,但是我发现了一个可能的,简单的,方法来解决这个问题使用shared_future可以复制(所以我可以推入一个向量)。 – Geowil