c++ - 如何制作一个只能在一个线程上同时执行的函数?
问题描述
我有一个用来查找素数的程序。它在多个线程上执行。我正在使用 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;
}
解决方案
使用互斥锁是一种有效的解决方案,但在这种情况下会导致不必要的开销。您可以简单地制作nextId
原子:
std::atomic<int> nextId{1};
这使得增量操作是GetNextNumber
原子的,所以没有两个线程会得到相同的值。
推荐阅读
- apache-kafka - 如何配置 Kafka 消费者只处理一次消息?
- r - 使用二元变量 R 进行线性优化
- entity-framework-extensions - EFPlus BulkInsert - 如何获取数据库生成的 ID
- php - PHP 中的 Paymaya 集成
- bluetooth - Android 设备与 Arduino 的蓝牙连接
- c# - C#- 在 dataGridView 的动态数据库表中查找列索引
- python - Python绘制到不同的数字失败
- php - 来自数据库的 PHP 电话号码格式
- asp.net-core - 如果在虚拟目录中发布,Asp.Net Core signalR 不起作用
- php - Laravel 5.6 漂亮的 URL 分页