gpt4 book ai didi

c++ - 带线程的错误结果处理 vector

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:01:17 26 4
gpt4 key购买 nike

EDIT: Question closed.

Suggested pow of elements

int mypow(int n) { return n * n; }transform(datos->origen->begin(),datos->origen->end(),datos->cuads->begin(),mypow);

I am trying to get the sum , the min and pow over an int vector concurrently.I am using ubuntu 11.10 , codelite and g++ with phtreads.

I fill the vector, and spawn a thread per task. But I got wrong result.

I think the code it's ok, but really not and I don't why.

Filling the int vector with 10 ints, I got the following execution:

Sum: 110Min: 2original container length:10246... to 20pow container lenght:20000... 10 zeros4  ----> true result after pow elements163664... rest of elementsMain thread ended

Thanks in advance

code:

#include <iostream>
#include <vector>

#include <pthread.h>

using std::cout;
using std::cin; // C++ uses
using std::endl;
using std::vector;


// struct to store results
typedef struct
{
int suma;
int min;
vector<int>* origen;
vector<int>* cuads;
}tdata;


// mutex
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;


// Adition funct
void *suma(void* ptr)
{

// lock mutex
pthread_mutex_lock( &mutex1 );

tdata* datos = reinterpret_cast<tdata*>(ptr);

// iterator
vector<int>::const_iterator it1 = datos->origen->begin();

while( it1 != datos->origen->end() )
{
datos->suma += *it1;
it1++;
}

pthread_mutex_unlock( &mutex1 );

return 0;
}

// minimun function
void* min(void *ptr)
{

pthread_mutex_lock( &mutex1 );

tdata* datos = reinterpret_cast<tdata*>(ptr);

datos->min = datos->origen->at(0); // inicializo el menor

vector<int>::const_iterator it2 = datos->origen->begin();

while( it2 != datos->origen->end())
{
if ( (*it2) < datos->min )
datos->min = (*it2);

it2++;
}

pthread_mutex_unlock( &mutex1 );
return 0;
}

// pow function. Dinamically alloc vector and fill it
void* cuadrados( void* ptr)
{

pthread_mutex_lock( &mutex1 );

tdata* datos = reinterpret_cast<tdata*>(ptr);

// Error int tan = static_cast<int>(datos->origen->size());

datos->cuads = new vector<int>(); // Error new vector<int>(tan);

vector<int>::const_iterator it3 = datos->origen->begin();

while( it3 != datos->origen->end() )
{
int n = (*it3) * (*it3);
datos->cuads->push_back(n);

it3++;
}
pthread_mutex_unlock( &mutex1 );
return 0;
}



int main(int argc, char **argv)
{

#define MAXHILOS 3 // nº de hilos
#define MAXNUMS 10 // cantidad de numeros

vector<int> enteros; // vector de enteros

pthread_t hilos[MAXHILOS]; // vector de hilos


// fill origin vector
for ( int i = 0; i < MAXNUMS; i++)
enteros.push_back((i+1)*2);


// init target structure
tdata t = {0};

// point to origin vector
t.origen = &enteros;

// thread creation
pthread_create(&hilos[0],NULL,suma,&t);
pthread_create(&hilos[1],NULL,min,&t);
pthread_create(&hilos[2],NULL,cuadrados,&t);

// wait until all threads ends
pthread_join(hilos[0], NULL);
pthread_join(hilos[1], NULL);
pthread_join(hilos[2], NULL);


// show results
cout << "Sum: " << t.suma << endl
<< "Min: " << t.min << endl;

cout << "original vector length:" << enteros.size() << endl;

vector<int>::const_iterator ent = enteros.begin();

while( ent != enteros.end() )
{
cout << (*ent) << endl;
ent++;
}

cout << "pow vector length:" << t.cuads->size() << endl;


vector<int>::const_iterator cuadr =t.cuads->begin();

while( cuadr != t.cuads->end() )
{
cout << (*cuadr) << endl;
cuadr++;
}


//delete[] t.cuads;
cout << "Main thread ended" << endl;

cin.get();
return 0;
}
EDIT: Yes, the trouble was creating the vector with fixed size.Thanks to all. 

最佳答案

我认为问题出在 tdata.cuads 开头的十个零 vector 。这是由以下原因引起的:

// This allocates a new vector with 'tan' number of ints
// and initialises them to zero.
datos->cuads = new vector<int>(tan);

// This loops appends new elements to the 'cuads' vector,
// after the ten zeros.
while( it3 != datos->origen->end() )
{
int n = (*it3) * (*it3);
datos->cuads->push_back(n);

it3++;
}

要更正此问题,请声明创建没有初始大小的 cuads:

datos->cuads = new vector<int>();                

while( it3 != datos->origen->end() )
{
int n = (*it3) * (*it3);
datos->cuads->push_back(n);

it3++;
}

或使用operator[] 填充cuads:

datos->cuads = new vector<int>(tan);                

size_t i = 0;
while( it3 != datos->origen->end() )
{
int n = (*it3) * (*it3);
*(datos->cuads)[i++] = n;
it3++;
}

其他一些小问题:

    在 C++ 中定义 struct 时不需要
  • typedef,只需 struct tdata { ... };
  • 您可以使用 std::accumulate() 来计算容器的总和,并使用 std::min_element() 来查找容器的最小值。<

例如:

dataos->suma = std::accumulate(dataos->origen->begin(), dataos->origen->end(), 0);
dataos->min = *std::min_element(dataos->origen->begin(), dataos->origen->end());

关于c++ - 带线程的错误结果处理 vector <int>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8979266/

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