我使用的是旧考试的学习指南和的问题之一是使用并行线程填写下面的代码:仍然感到困惑的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);
}
我们现在应该做的是让我们的并行线程模仿此代码:
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;
}
我已经真的迷失在这一节,我相信我不理解它,以及我应该(或根本)。希望能够帮助我理解任何答案。
'local_data * local'是一个指针声明,所以'local.a'应该是'local-> a'。 –
@ K-ballo感谢您的支持! – raphnguyen
您已编辑原始文章以包含@Brendan的答案。你还有问题吗?如果是这样,您应该添加更多信息来帮助我们找出问题所在。如果不是,你应该接受布伦丹的回答。 – jswolf19