2011-10-03 87 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