我使用旧考试作为学习指南,其中一个问题是使用pthreads填写以下代码:
#include <pthread.h>
#include <stdio.h>
typedef struct {
int a;
int b;
} local_data;
void *foo(void *arg);
int main() {
int a = 12;
int b = 9;
pthread_t tid;
pthread_attr_t attr;
local_data local;
local.a = a;
local.b = b;
pthread_attr_init(&attr);
/* block of code we are supposed to fill in (my attempt at filling it in)
pthread_create(&tid, &attr, foo, &local);
pthread_join(tid, NULL);
*/
b = b - 5;
printf("program exit. a = %d, b = %d\n", a, b);
return 0;
}
void *foo(void *arg) {
int a, b;
local_data *local = (local_data*)arg;
/* block of code we are supposed to fill in (my attempt at filling it in)
a = local->a;
b = local->b;
a++;
*/
printf("program exit. a = %d, b = %d\n", a, b);
pthread_exit(0);
}
我们应该做的是让我们的pthreads模仿这段代码:
int main() {
int a = 12;
int b = 9;
int fid = fork();
if (fid == 0) {
a++;
}
else {
wait(NULL);
b = b - 5;
}
printf("program exit. a = %d, b = %d\n", a, b);
return 0;
}
我真的迷失在这一部分,我确信我不理解它(或者根本不理解)。非常感谢任何帮助我掌握这个概念的答案。
答案 0 :(得分:5)
这一行错了:
pthread_create(&tid, &attr, foo(local), NULL);
pthread_create
的签名是:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg);
第三个参数是一个函数,最后一个参数是它的参数,所以不是调用函数(foo(local)
),而是分别传递函数和参数:
pthread_create(&tid, &attr, foo, &local);