gpt4 book ai didi

c++ - 如何制作只能在一个线程上同时执行的功能?

转载 作者:行者123 更新时间:2023-12-02 09:56:07 25 4
gpt4 key购买 nike

我有一个用于查找素数的程序。它正在多个线程上执行。我正在对线程调用GetNextNumber()函数,以获取一个数字以检查它是否为质数,但是似乎该函数同时由多个线程执行,因此有时两个线程会获得相同的数字。这是我的代码:

#include "pch.h"
#include <cmath>
#include <fstream>
#include <thread>
#include <iostream>
#include <string>

int nextInt = 1;
std::ofstream file;

bool TestPrime(int number)
{
double rootInt = sqrt(number);
for (int i = 3; i <= rootInt; i += 2)
{
double divValue = (double)number / i;
if (int(divValue) == divValue)
{
return false;
}
}
return true;
}
int GetNextNumber()
{
return (nextInt += 2);
}

void PrimeFinderThread()
{
while (true)
{
int number = GetNextNumber();
bool isPrime = TestPrime(number);
if (isPrime)
{
std::string fileOutput = std::to_string(number) + "-";
file << fileOutput;
}
}
}

int main() {
file.open("primes.txt", std::ofstream::app);
file << 2 << "-";
std::thread threads[4];
for (int i = 0; i < 4; i++) {
threads[i] = std::thread(PrimeFinderThread);
}
for (int i = 0; i < 4; i++) {
threads[i].join();
}
return 0;
}

最佳答案

std::mutexstd::lock_guard一起使用。这将阻止同时执行该功能。

#include "pch.h"
#include <cmath>
#include <fstream>
#include <thread>
#include <iostream>
#include <string>
#include <mutex>

int nextInt = 1;
std::ofstream file;

bool TestPrime(int number)
{
double rootInt = sqrt(number);
for (int i = 3; i <= rootInt; i += 2)
{
double divValue = (double)number / i;
if (int(divValue) == divValue)
{
return false;
}
}
return true;
}
int GetNextNumber()
{
static std::mutex m;
const std::lock_guard<std::mutex> lock(m);
return (nextInt += 2);
}

void PrimeFinderThread()
{
while (true)
{
int number = GetNextNumber();
bool isPrime = TestPrime(number);
if (isPrime)
{
std::string fileOutput = std::to_string(number) + "-";
file << fileOutput;
}
}
}

int main() {
file.open("primes.txt", std::ofstream::app);
file << 2 << "-";
std::thread threads[4];
for (int i = 0; i < 4; i++) {
threads[i] = std::thread(PrimeFinderThread);
}
for (int i = 0; i < 4; i++) {
threads[i].join();
}
return 0;
}

关于c++ - 如何制作只能在一个线程上同时执行的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60019360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com