首页 > 解决方案 > 如何制作一个只能在一个线程上同时执行的函数?

问题描述

我有一个用来查找素数的程序。它在多个线程上执行。我正在使用 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;
}

标签: c++multithreadingsimultaneous

解决方案


使用互斥锁是一种有效的解决方案,但在这种情况下会导致不必要的开销。您可以简单地制作nextId原子:

std::atomic<int> nextId{1};

这使得增量操作是GetNextNumber原子的,所以没有两个线程会得到相同的值。


推荐阅读