我正在爲一個遊戲提供概念證明測試程序,其中某些操作被線程化並且信息輸出到每個線程的命令窗口。到目前爲止,我已經獲得了基本的線程處理工作,但似乎我的被調用函數中的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