gpt4 book ai didi

c - 仍然对Pthreads感到困惑

转载 作者:行者123 更新时间:2023-12-03 12:49:51 25 4
gpt4 key购买 nike

我正在使用旧考试作为学习指南,其中一个问题是使用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;
}

我在本节中确实迷失了自己,我确信我对它的理解不如应有的(或根本不了解)。希望能得到任何答案,以帮助我掌握这一概念。

最佳答案

这行是错误的:

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);

关于c - 仍然对Pthreads感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7630874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com