我正在实现一个堆栈池,以便在特定数量的线程中执行一些基本运算。
这是代码:
int add(int a, int b) {return a+b;}
int sub(int a, int b) {return a-b;}
int mul(int a, int b) {return a*b;}
sem_t sem_ops;
void* compute(void* arg){
Args *args = arg;
Operation* op = args->operation;
printOP(*op);
int * value = malloc ( sizeof ( int ) ) ;
* value = op->op(op->a, op->b);
args->is_complete = true;
sem_post(&sem_ops);
return value;
}
void push(Operation op , Queue* q){
q->operations[++(q->last)] = op;
}
Operation *pop(Queue *q){
q->first++;
return &q->operations[q->first];
}
int size(Queue *q){
return q->last - q->first;
}
bool read_operations(char* filename, Queue* ops){
printf("reading from file %sn",filename);
FILE *fp = fopen(filename, "r");
if(fp == NULL )
{
printf("couldnt open");
return false;
}
int id,a,b;
while(!feof(fp)){
fscanf(fp,"%d %d %dn",&id,&a,&b);
Operation op;
op.a = a;
op.b = b;
switch (id){
case 0:
op.op = add;
break;
case 1:
op.op = sub;
break;
case 2:
default:
op.op =mul;
break;
}
push(op,ops);
}
return true;
}
ArrayList* execute_thread_pool(char* filename, int poolSize){
sem_init(&sem_ops,0,poolSize);
//init return value
ArrayList* retval =malloc(sizeof(ArrayList));
int res [ TOTAL_OP_COUNT];
retval->results = res;
retval->count = 0;
// populate Q
Queue q;
Operation ops[TOTAL_OP_COUNT];
q.first = 0;
q.last = 0;
q.max = TOTAL_OP_COUNT;
q.operations = ops;
read_operations(filename,&q);
// thread tids
pthread_t threads[TOTAL_OP_COUNT];
//args for each thread
Args args[TOTAL_OP_COUNT];
int* result= NULL;
for(int i =0; i<poolSize; ++i){
sem_wait(&sem_ops);
args[i].operation = pop(&q);
args[i].is_complete=false;
pthread_create(&threads[i],NULL, compute,&args[i]);
}
for(int i =0; i<poolSize; ++i){
if(args[i].is_complete){
pthread_join(threads[i],(void**) result);
res[i] = *result; // line 88
}else --i;
}
return retval;
}
和structs typedefs:
typedef struct _Operation{
int(*op) (int, int);
int a;
int b;
} Operation;
typedef struct _Args{
Operation* operation;
bool is_complete;
}Args;
typedef struct _Queue{
Operation* operations;
int last;
int first;
int max;
}Queue;
我试过在几个不同的地方使用malloc,但无法摆脱segfault。这是主要功能的内容:
ArrayList *al =malloc(sizeof(ArrayList)) ;
al = execute_thread_pool("bob.txt", 4);
在gdb中,bt如下:
#0 0x0000555555555762 in execute_thread_pool (filename=0x555555556004 "bob.txt", poolSize=4) at pool.c:88
#1 0x00005555555552db in main (argc=1, argv=0x7fffffffda68) at main.c:5
我已经研究了几个小时,尝试了多种方法,尝试了不使用信号量和使用不那么有趣的循环,但结果是一样的。有人能帮我找出问题吗?
您误解了pthread_join
调用以及模拟传递引用的工作原理。
您应该使用指向运算符&
:的指针来传递指向int *
变量的指针
pthread_join(threads[i], &result);
您还应该记住free
指针result
,否则会发生内存泄漏。