- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试创建一个多线程程序,该程序将 N 个随机数 [-100,100] 的数组与 K 个工作线程相加,这些工作线程由程序员实现的自旋锁(忙等待)序列化。在尝试使用随机数之前,出于测试目的,我将整个数组初始化为 1,正如您将在我的代码中看到的那样。由于我不知道问题出在哪里,所以我将发布完整代码:
#include <iostream>
#include <string.h>
#include <pthread.h>
#include <cstdlib>
#include <time.h>
#include <atomic>
#include <chrono>
using namespace std;
using namespace chrono;
struct lock {
long double sum = 0;
atomic_flag m_flag = ATOMIC_FLAG_INIT; // Inicializa com m_flag = 0
void acquire() {
while(m_flag.test_and_set());
}
void release() {
m_flag.clear();
}
};
struct t_data{
int t_id;
char* sumArray;
struct lock* spinlock;
};
void* sum(void* thread_data) {
struct t_data *my_data;
long double m_sum=0;
my_data = (struct t_data *) thread_data;
for (int i=0;i<strlen(my_data->sumArray);i++) {
m_sum += my_data->sumArray[i];
}
my_data->spinlock->acquire();
cout << "THREAD ID: " << my_data->t_id << endl;
cout << "Acquired lock." << endl;
my_data->spinlock->sum += m_sum;
cout << "Releasing lock..." << endl << endl;
my_data->spinlock->release();
}
int main(int argc, char** argv) {
// Inicializar cronômetro, arrays, spinlock,etc. , spinlock, etc.
system_clock::time_point starting_time = system_clock::now();
int K = atoi(argv[1]);
int N = atoi(argv[2]);
int temp;
double expected_sum = 0;
pthread_t threads[K];
struct t_data threads_data[K];
struct lock spinlock;
const long int numElements = (long int) N/K; //Divisão inteira de N/K para dividir array em parcelas
// Criar array[K] de arrays para delegar cada sub-lista a uma thread
char** numArrays = new char*[K];
for(int i=0;i<K;i++)
numArrays[i] = new char[numElements]; //Char utilizado para que seja alocado apenas 1 byte por número
// Inicializar seed aleatória para preenchimento de arrays
srand(time(NULL));
//Preencher arrays que serão passados às threads criadas
for (int i=0;i<K;i++) {
for(int j=0;j<numElements;j++) {
temp = 1;//rand() % 201 - 100; (CHANGING THIS GIVES UNEXPECTED RESULTS)
numArrays[i][j] = temp;
expected_sum+=temp;
}
//Criar threads e passando argumentos(id,spinlock,array)
threads_data[i].t_id = i;
threads_data[i].spinlock = &spinlock;
threads_data[i].sumArray = numArrays[i];
pthread_create(&threads[i],NULL,sum,(void*)&threads_data[i]);
}
// Parar o programa até que todas as threads terminem para imprimir soma correta
for (int i=0;i<K;i++){
if(pthread_join(threads[i],NULL)) cout << "Error waiting for threads." << endl;
}
// Somando últimos valores restantes no caso de N%K != 0 (esta parcela torna-se irrelevante à medida que N >> K)
for(int i=0;i<(int)N%K;i++) {
temp = 1;//rand() % 201 - 100; (CHANGING THIS GIVES UNEXPECTED RESULTS)
spinlock.sum+=temp;
expected_sum+=temp;
}
// Printar resultado esperado, o calculado e tempo de execução
cout << "EXPECTED SUM = " << expected_sum << endl;
cout << "CALCULATED SUM = " << spinlock.sum << endl;
// Liberar memória alocada
for(int i=0;i<K;i++)
delete[] numArrays[i];
delete[] numArrays;
auto start_ms = time_point_cast<milliseconds>(starting_time);
auto now = system_clock::now();
auto now_ms = time_point_cast<milliseconds>(now);
auto value = now_ms - start_ms;
long execution_time = value.count();
cout << "-----------------------" << endl;
cout << "Execution time: " << execution_time << "ms" << endl;
return 0;
}
这在计算总和时效果很好,但会带来执行时间问题:它应该与 (N/K) 成线性比例,但测试 K=10,N=10⁶:
EXPECTED SUM = 1e+06
CALCULATED SUM = 1e+06
-----------------------
Execution time: 1310ms
并且 K=10,N=2*10⁶:
EXPECTED SUM = 2e+06
CALCULATED SUM = 2e+06
-----------------------
Execution time: 7144ms
我不知道为什么会这样。应该加倍。更改 K 正常工作。另外,如果我使用 rand() % 201-100
而不是 1,事情就会变得一团糟。对于 K=10,N=10⁶:
EXPECTED SUM = -16307
CALCULATED SUM = 1695
-----------------------
Execution time: 95ms
关于执行时间的变化,N 是固定的(线性缩放)但 K 不再有任何区别。这些对我来说都没有意义。
提前致谢!
最佳答案
strlen(my_data->sumArray)
将停在第一个 0
在字符数组/c 字符串中继续总结 temp
expected_sum
的值.使用 vector
对于非 ascii 数据(毕竟这是 C++):
// use a vector in t_data
struct t_data{
int t_id;
std::vector<char> sumArray;
lock* spinlock;
};
// adjust summing up in sum(void* thread_data)
for (char value : my_data->sumArray) {
m_sum += value;
}
// initialise like this
threads_data[i].sumArray.resize(numElements);
for(size_t j = 0; j < threads_data[i].sumArray.size(); ++j) {
char temp = 1; //or (char)(rand() % 201 - 100);
threads_data[i].sumArray[j] = temp;
expected_sum += temp;
}
现在考虑一下你的时间安排:移动 threads_data[i]
的初始化和 expected_sum
在计时区域之外,否则数百万rand
电话肯定会主宰一切。在任何情况下,您都在测量顺序版本和并行版本,因此您不能指望 K
在时间上有所不同:您总是至少测量顺序版本 + 最后一个并行版本(加入时)。
关于c++ - 多线程执行时间与随机数之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37287511/
我编写了一个函数来随机从 [-10,10] 中获取一对。 import System.Random main = do { s State g a randomSt = S
好的,我了解如何在 Scala 中实现随机数生成器以及如何设置生成的随机数的上限,但我对如何更改下限感到困惑。例如: var computerGuess= scala.util.Random
我写了一个函数来从 [-10,10] 中随机得到一对。 import System.Random main = do { s State g a randomSt = St
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
我正在做一个项目,我需要在其中生成 8 个随机数。由于某种原因,我遇到随机数部分非常耗时的问题。 8 个随机数的意思是我需要一个由数字 0-9 组成的 8 个字符长的字符串。例如 01234567 或
这个问题已经有答案了: Why do I always get the same sequence of random numbers with rand()? (12 个回答) 已关闭 9 年前。
我看到这个问题可能已经在这里得到回答:Random using WELL512 但是,它对用户不太友好,也没有提供如何在“真实世界”的代码片段中使用它的示例。 这是我目前拥有的: #define m
我想知道是否有人可以为我澄清这一行。 Create a function die(x) which rolls a die x times keeping track of how many time
我正在制作一款有 6 名防守球员的足球比赛。我将这段代码设置为随机让他们都向四分卫移动。 我想知道是否有更好的方法来做到这一点。我知道必须有一种方法可以在没有这么多 if 语句的情况下循环它,但我对
在以下位置:http://www.fredosaurus.com/notes-cpp/misc/random.html 它提到如果我们想生成一个1-10范围内的随机数,我们可以这样做: r = (ra
如何在 Linux 和 C++ 中使用随机数? 我找到了一些我想使用的代码,它有一行 srand((unsigned)time(0));//seed 但是 gcc 说 board.cpp:94:24:
这个问题在这里已经有了答案: Generating random whole numbers in JavaScript in a specific range (40 个答案) 关闭 9 年前。
我有以下脚本: Timer=0; function countdown(auctionid){ var auctions; var divs; Timer=Timer+1;
利用oracle的dbms_random包结合rownum来实现,示例如下,随机取499户: select * from ( select * from busi.t_ar_
我需要获取随机数,但它不应该等于之前的数字。这是我的一段代码。但这不起作用。 function getNumber(){ var min = 0; var max = 4; var i;
我对 Haskell 还很陌生。我有一个数据类型: data Sentence= Prop Int | No Sentence | And [Sentence]
已关闭。这个问题是 not reproducible or was caused by typos 。目前不接受答案。 这个问题是由拼写错误或无法再重现的问题引起的。虽然类似的问题可能是 on-top
这个问题已经有答案了: How do I generate random integers within a specific range in Java? (73 个回答) 已关闭 7 年前。
function getRandomArbitrary(min, max) { var r = Math.floor(Math.random() * (max - min + 1) + m
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: Generate random number with non-uniform density 我尝试识别/
我是一名优秀的程序员,十分优秀!