더 큰 프로그램을위한 기본 코드를 작성하려고합니다. 원래 코드는 내 계산 결과를 txt 파일에 작성한다고 가정했지만 여기서는 코드를 단순화하기 위해 숫자 1을 작성하도록 변경했습니다. 문제는 내가 얻을 것이라고 생각하는 수를 얻지 못한다는 것입니다 ... 1000 장의 1 장을 인쇄하면 각각 1 장씩 더 크고 난수를 얻습니다 ...
내 코드의 문제점은 무엇입니까?
(나는 Windows 10, 코드 블록 작업 공간을 사용하고 있으며 C ++로 코드를 작성하고 있습니다)
코드:
#include <iostream>
#include <thread>
#include <vector>
#include <fstream>
using namespace std;
ofstream myfile;
void doTask()
{
myfile << "1\n";
}
void f()
{
vector<thread> threads;
for(int i = 0; i < 10; ++i)
{
threads.push_back(thread(doTask));
}
for(int j=0; j<10; j++) threads[j].join();
threads.erase(threads.begin(), threads.end());
}
int main()
{
myfile.open("a.txt");
for(int i=0; i<100; i++) f();
myfile.close();
return 0;
}
모두 감사합니다!
ofstream 스레드를 안전하게 만드십시오. 다음은 할 것입니다.
#include <iostream>
#include <thread>
#include <vector>
#include <fstream>
#include <mutex>
using namespace std;
ofstream myfile;
std::mutex myMutex;
void doTask()
{
myMutex.lock();
myfile << "1\n";
myMutex.unlock();
}
void f()
{
vector<thread> threads;
for(int i = 0; i < 10; ++i)
{
threads.push_back(thread(doTask));
}
for(int j=0; j<10; j++) threads[j].join();
threads.erase(threads.begin(), threads.end());
}
int main()
{
myfile.open("a.txt");
for(int i=0; i<100; i++) f();
myfile.close();
return 0;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다