2011-10-03 38 views
2

我使用的是旧考试的学习指南和的问题之一是使用并行线程填写下面的代码:仍然感到困惑的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; 
} 

我已经真的迷失在这一节,我相信我不理解它,以及我应该(或根本)。希望能够帮助我理解任何答案。

+1

'local_data * local'是一个指针声明,所以'local.a'应该是'local-> a'。 –

+0

@ K-ballo感谢您的支持! – raphnguyen

+2

您已编辑原始文章以包含@Brendan的答案。你还有问题吗?如果是这样,您应该添加更多信息来帮助我们找出问题所在。如果不是,你应该接受布伦丹的回答。 – jswolf19

回答

5

此行是错误的:

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

'b'也需要在线程函数中初始化。 – jswolf19

+0

@Brendan谢谢!我不太明白语法。这清除了一点。 – raphnguyen

+0

@ jswolf19感谢您的支持。 – raphnguyen