gpt4 book ai didi

linux - 以不确定的方式使用 pthreads 时出现段错误

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

问题是当我在单核上运行下面的代码时,有时它运行正确,有时我会遇到段错误。可能这个问题在多核机器上会更频繁地发生。我需要知道这种不确定性是在我的程序中引入的,我该如何解决它。谢谢。

int numThreads = 4;

class Evaluator;

struct E {
Evaluator* evaluator;
int id;
};

class Evaluator {
public:
pthread_t * threads;
sem_t* fork_sync;
sem_t* join_sync;
int tin;
pthread_mutex_t tin_mut;

double * d;
int sz;
int cursor;
pthread_mutex_t c_mut;

Evaluator(sem_t* fs, sem_t* js) {
fork_sync = fs;
join_sync = js;
threads = new pthread_t[numThreads];
tin = 0;
pthread_mutex_init(&tin_mut,NULL);
for(int i=0 ;i<numThreads; i++) {
E arg;
arg.evaluator = this;
arg.id = i;
pthread_create(&threads[i],NULL,(void* (*) (void*) )func,(void*)&arg);
}


//dummy init
sz = 20;
d = new double[sz];
for(int i=0; i<sz ; i++) d[i] = .5 + i;
cursor = 0;
pthread_mutex_init(&c_mut,NULL);
}

static void func(E* e) {
Evaluator* eval = e -> evaluator;
eval -> go(e -> id);
}

void reset() {
cursor = 0;
}

void go(int id) {
while(1) {
sem_wait(fork_sync);

pthread_mutex_lock(&tin_mut);
++tin;
pthread_mutex_unlock(&tin_mut);

while(1) {
int idx;
pthread_mutex_lock(&c_mut);
idx = cursor++;
pthread_mutex_unlock(&c_mut);
if(idx >= sz ) break;
// do the evaluation
cout << "evaluating index " << idx << " using thread " << id << endl;
}

int remain;
pthread_mutex_lock(&tin_mut);
remain = --tin;
pthread_mutex_unlock(&tin_mut);
if(remain == 0) sem_post(join_sync);
}
}


};

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

sem_t fork_sync;
sem_t join_sync;

sem_init(&fork_sync,0,0);
sem_init(&join_sync,0,0);

Evaluator e(&fork_sync,&join_sync);


//evaluating t times
int t = 3;
for(int i=0; i<t; i++) {
cout << "---------- evaluation number :" << i << endl;
e.reset();
for(int j=0; j<numThreads; j++) sem_post(&fork_sync);
sem_wait(&join_sync);
cout << endl;
}

return 0;
}

最佳答案

arg 在堆栈上。您正在获取它的地址并将该地址传递给另一个线程。竞争条件(堆栈上的值可以在新创建的线程读取它之前被覆盖)。

E arg;
arg.evaluator = this;
arg.id = i;
pthread_create(&threads[i],NULL,(void* (*) (void*) )func,(void*)&arg);

解决方法:

E* arg = new E();
arg->evaluator = this;
arg->id = i;
pthread_create(&threads[i],NULL,(void* (*) (void*) )func,(void*)arg);

并且不要忘记在 func删除 e

关于linux - 以不确定的方式使用 pthreads 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1944602/

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