我使用的是舊考試的學習指南和的問題之一是使用並行線程填寫下面的代碼:仍然感到困惑的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