Still confused about Pthreads

Refresh

December 2018

Views

122 time

2

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.

1 answers

5

Эта линия не так:

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

pthread_create«S подпись:

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