c++多线程中断

C++ multithreading interruptions

本文关键字:中断 多线程 c++      更新时间:2023-10-16

您可以在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(包括新行),然后通过单个函数调用将其写入控制台。单个函数调用将帮助控制台编写器一次只写入一个缓冲区的内容。