开发者

Still confused about Pthreads

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(&at开发者_Python百科tr);

    /* 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.


This line is wrong:

pthread_create(&tid, &attr, foo(local), NULL);

pthread_create's signature is:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    void *(*start_routine)(void*), void *arg);

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:

pthread_create(&tid, &attr, foo, &local);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜