【发布时间】:2016-02-14 15:28:20
【问题描述】:
正如您在主函数中看到的,我创建了一组线程,它们执行完全相同的函数但具有不同的参数。该函数只是打印出向量的值。现在的问题是这些线程相互干扰。我的意思是一个线程在另一个线程开始之前没有完成打印(cout),它就像 sdkljasjdkljsad。我想要某种混乱的顺序,例如:
Thread 1 Vector[0]
Thread 2 Vector[0]
Thread 1 Vector[1]
Thread 3 Vector[0]
Thread 4 Vector[0]
Thread 2 Vector[1]
而不是:
Thread 1 Thread 2 Vector[0] Vector[0]
Thread 2 Vector[1]
Thread 1 Thread 4 Vector[1] Thread 3 Vector[0] Vector[1]
我该如何解决这个问题?附言数据文件只是球员姓名、体重和每行卧推的列表。将这些转换为字符串并放入向量中(是的,听起来很愚蠢,但我只是在完成一项任务)。
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <string>
#include <thread>
#include <sstream>
#include <iomanip>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
using namespace std;
vector<string> Kategorijos;
vector< vector<string> > Zaidejai;
ifstream duom("duom.txt");
string precision(double a) {
ostringstream out;
out << setprecision(6) << a;
return out.str();
}
void read() {
string tempKat;
int tempZaidSk;
vector<string> tempZaid;
string vardas;
int svoris;
double pakeltasSvoris;
while (duom >> tempKat >> tempZaidSk) {
Kategorijos.push_back(tempKat);
for (int i = 0; i < tempZaidSk; i++) {
duom >> vardas >> svoris >> pakeltasSvoris;
tempZaid.push_back(vardas + " " + to_string(svoris) + " " + precision(pakeltasSvoris));
}
Zaidejai.push_back(tempZaid);
tempZaid.clear();
}
duom.close();
}
void writethreads(int a) {
int pNr = a+1;
for (int i = 0; i < (int)Zaidejai[a].size(); i++) {
cout << endl << "Proceso nr: " << pNr << " " << i << ": " << Zaidejai[a][i] ;
}
}
void print() {
for (int i = 0; i < (int)Kategorijos.size(); i++) {
cout << "*** " << Kategorijos[i] << " ***" << endl;
for (int j = 0; j < (int)Zaidejai[i].size(); j++) {
cout << j+1<<") "<< Zaidejai[i][j] << endl;
}
cout << endl;
}
cout << "-------------------------------------------------------------------" << endl;
}
int main()
{
read();
print();
boost::thread_group threads
;
for (int i = 0; i < (int)Kategorijos.size(); i++) {
threads.create_thread(boost::bind(writethreads, i));
}
threads.join_all();
system("pause");
return 0;
}
【问题讨论】:
-
我必须使用线程以及控制台,这些是任务的要求。我用 Java 做过同样的事情,唯一的区别是我一个接一个地创建了 5 个独立的线程,而且效果很好。但是,这有点取决于情况,因为我知道数据文件中有 5 个数据块。使用 c++,我想确保可以在不接触代码的情况下更改数据文件,这就是我使用 for 循环和线程组的原因。
标签: c++ multithreading c++11