c++多线程中断
C++ multithreading interruptions
您可以在main函数中看到,我创建了一组线程,它们执行完全相同的函数,但具有不同的参数。该函数只是打印出vector的值。现在的问题是这些线程相互干扰。我的意思是,一个线程在另一个线程开始之前没有完成打印(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;
}
欢迎讨论线程同步问题!当一次只有一个线程可以使用一个资源时,用于控制该资源的锁是互斥锁。您还可以存储一个线程的数据,以便在最后输出,或者您可以让线程在barrier处同步。
控制台写道,您可以使用适当的互斥锁同步它们。但是在本例中,对于控制台输出,可能根本不使用线程。否则将打印发送到处理它的专用线程。
使用通常的cout
重载operator <<
的替代方法是将内容写入本地缓冲区或stringsteam
(包括新行),然后通过单个函数调用将其写入控制台。单个函数调用将帮助控制台编写器一次只写入一个缓冲区的内容。
相关文章:
- 在C++中使用cURL和多线程
- 多线程双缓冲区
- 为什么我的多线程作业队列崩溃
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 试图创建一个多线程程序来查找0-100000000之间的总素数
- 为什么一个向量上的多线程操作很慢
- 学习多线程C++:添加线程不会使执行速度更快,即使它看起来应该
- 全局变量 多读取器 一个写入器多线程安全?
- boost::文件系统::recursive_directory_iterator多线程安全
- 如何阻止TensorFlow的多线程
- 如何在多线程中正确使用unique_ptr进行多态性?
- 并发/多线程:是否可以以这种方式生成相同的输出?
- sigwait() 在多线程程序中不起作用
- 多线程程序中出现意外的内存泄漏
- 静态 constexpr 类成员变量对多线程读取是否安全?
- 使用 shared_ptr 在中断时结束多线程循环
- 多线程应用程序中的零MQ处理中断
- 多线程程序因"Alarm Clock"而中断
- c++多线程中断
- linux多线程应用程序中的中断会生成SIGSEGV