我想使用线程来为数组填充值(每个线程的数组的所有元素的值都相同,但不同的线程具有不同的值)。 在这段代码中我遇到了一个问题,当我设置开始而没有线程必须在数组中填充的元素时,它没有为第一个线程正确设置,其余似乎工作正常..有人可以帮我弄清楚我哪里出错了,我想这样做没有锁,帮助将非常感谢!! 示例no threads = 2 数组大小= 3 第一个线程将填充前2个元素,第二个线程将填充最后3个元素..
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int* array;
struct variables
{
int start;
int elements;
int value;
};
void* runner(void *param)
{
//int e=atoi((char*)param);
variables* a=(struct variables*)param;
cout<<"start="<<a->start<<endl;
cout<<"elements"<<a->elements<<endl;
cout<<"value"<<a->value<<endl;
for(int i=a->start, j=0; j<a->elements; i++, j++ )
{
array[i]=a->value;
}
}
int main()
{
pthread_t tid[10];
int noOfThreads, sizeOfArray;
cout<<"No of threads (between 1-20): ";
cin>>noOfThreads;
cout<<"size of array: ";
cin>>sizeOfArray;
array = new int[sizeOfArray];
int e=sizeOfArray/noOfThreads;
//int start=0;
for(int i=0,j=0; i<noOfThreads; i++)
{
variables v;
cout<<"i="<<i<<endl;
v.start=(e*j);
cout<<"v.start="<<v.start<<endl;
cout<<"j="<<j<<endl;
if(i==(noOfThreads-1))
{
e=sizeOfArray-(e*(noOfThreads-1));
cout<<"e="<<e<<endl;
}
cout<<"Enter the value for Thread "<<i+1<<":";
cin>>v.value;
v.elements=e;
pthread_create(&tid[i], NULL, runner,&v);
j++;
}
for(int i=0; i<noOfThreads; i++)
{
pthread_join(tid[i], NULL);
}
for(int i=0; i<noOfThreads; i++)
{
cout<<"tid="<<tid[i]<<endl;
}
cout<<"printing array"<<endl;
for(int i=0; i<sizeOfArray; i++)
{
cout<<array[i]<<" ";
}
}
答案 0 :(得分:1)
你在堆栈上创建variables v
,将指针传递给线程,v在循环迭代中超出范围,重新分配[相同]内存并重写start元素和值,所有线程将具有相同的指针(相同的结构)我相信,除非他们退出比过期更快。把它放在跑步者:cout << params
中,检查我是否正确。
答案 1 :(得分:1)
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int* array;
struct variables
{
int start;
int elements;
int value;
};
void* runner(void *param)
{
//int e=atoi((char*)param);
variables* a=(struct variables*)param;
cout<<"start="<<a->start<<endl;
cout<<"elements="<<a->elements<<endl;
cout<<"value="<<a->value<<endl;
for(int i=a->start, j=0; j<a->elements; i++, j++ )
{
array[i]=a->value;
}
}
int main()
{
pthread_t tid[10];
int noOfThreads, sizeOfArray;
cout<<"No of threads (between 1-20): ";
cin>>noOfThreads;
cout<<"size of array: ";
cin>>sizeOfArray;
array = new int[sizeOfArray];
variables* v = new variables[noOfThreads];
int e=sizeOfArray/noOfThreads;
for (int i=0;i<noOfThreads;i++) {
v[i].start = e*i;
if(i==(noOfThreads-1)) {
v[i].elements=sizeOfArray-(e*(noOfThreads-1));
} else {
v[i].elements=e;
}
cout<<"Enter the value for Thread "<<i+1<<":";
cin>>v[i].value;
}
for(int i=0; i<noOfThreads; i++) {
pthread_create(&tid[i], NULL, runner,&v[i]);
}
for(int i=0; i<noOfThreads; i++)
{
pthread_join(tid[i], NULL);
}
for(int i=0; i<noOfThreads; i++)
{
cout<<"tid="<<tid[i]<<endl;
}
cout<<"printing array"<<endl;
for(int i=0; i<sizeOfArray; i++)
{
cout<<array[i]<<" ";
}
}