仍然对 Pthreads 感到困惑
我正在使用旧考试作为学习指南,其中一个问题是使用 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;
}
我真的对这一部分迷失了,我确信我没有理解它(或者根本没有理解)。如果有任何答案可以帮助我理解这个概念,我将不胜感激。
I am using an old exam as a study guide and one of the questions is to use pthreads to fill in the following code:
#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);
}
What we are supposed to do is make our pthreads mimic this code:
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;
}
I've been really lost on this section and I am sure I do not understand it as well as I should (or at all). Would appreciate any answers to help me grasp the concept.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这一行是错误的:
pthread_create
的签名是:第三个参数是一个函数,最后一个参数是它的参数,因此不要调用函数 (
foo(local)
),而是分别传递函数和参数:This line is wrong:
pthread_create
's signature is:The third argument is a function and the last argument is it's argument, so instead of calling the function (
foo(local)
), pass the function and the argument separately: