2016-04-27 106 views
-1

我該如何重寫這段代碼來使用進程而不是線程?我嘗試用C語言學習過程編程。我不知道我該怎麼做。這段代碼使用線程。關於這個algoritmus更多信息是這裏第153頁 - 158:線程處理

http://www.greenteapress.com/semaphores/downey08semaphores.pdf

#include <stdio.h> 
#include <stdlib.h> 
#include <semaphore.h> 
#include <pthread.h> 

#define MAX_PASSENGERS 500 

sem_t loading, loaded, unloading, unloaded; 

int n, c; 

void *passenger (void *tid) { 
    int i = *((int*) tid); 

    while (1) { 

    sem_wait(&loading); 
    printf("pass(i=%d).board()\n", i); 
    sem_post(&loaded); 

    sem_wait(&unloading); 
    printf("pass(i=%d).unboard()\n", i); 
    sem_post(&unloaded); 

    } 
} 

void *roller_coaster() { 
    while (1) { 

    printf("car.load(c=%d)\n", c); 
    for (int i = 0; i < c; i++) { 
     sem_post(&loading); 
    } 

    // wait for c passengers to load 
    for (int i = 0; i < c; i++) { 
     sem_wait(&loaded); 
    } 

    printf("car.run()\n"); 

    sleep(1); 

    printf("car.unload(c=%d)\n", c); 
    for (int i = 0; i < c; i++) { 
     sem_post(&unloading); 
    } 

    // wait for c passengers to unload 
    for (int i = 0; i < c; i++) { 
     sem_wait(&unloaded); 
    } 

    } 
} 

int main() { 

    printf("Number of passengers(n, n <= 500): "); 
    scanf("%d", &n); 
    printf("Number of passengers per cart(c, c < n): "); 
    scanf("%d", &c); 

    sem_init(&loading, 0, 0); 
    sem_init(&unloading, 0, 0); 

    sem_init(&loaded, 0, 0); 
    sem_init(&unloaded, 0, 0); 

    pthread_t car; 
    pthread_t tid[MAX_PASSENGERS]; 

    int my_ids[MAX_PASSENGERS]; 

    pthread_create(&car, NULL, roller_coaster, NULL); 

    for (int i = 0; i < n; i++) { 
    my_ids[i] = i; 
    pthread_create(&tid[i], NULL, passenger, &my_ids[i]); 
    } 

    pthread_join(car, NULL); 

    return 0; 
} 

感謝所有幫助球員

+0

您可以使用任何形式的[IPC](https://en.wikipedia.org/wiki/Inter-process_communication)來實現消息傳遞,這是一個好的開始。您可以使用套接字或命名/匿名管道等來完成此操作。閱讀鏈接以開始使用(; – Linuxxon

+0

您可以重構代碼並使用[fork](http://linux.die.net/man/2/fork)a子進程以及發送/接收數據之間的管道。請記住,在孩子們工作的時候,你需要保持父進程的某種循環。 – alexJones

回答

1

對於使用過程中,而不是線程,你需要用一種方法來替代pthread_create()電話使用fork()

然後父進程將繼續在本地繼續執行您的pthread_create()之後的內容。然後

孩子將調用傳遞的方法。

新創建過程的pid將採取tid作用。

由於您似乎已經在使用posix信號量,因此這種方法將繼續有效。但是,您需要使用已命名的信號量(請參見sem_open),並在子進程中(在調用方法之前)在進程中共享信號量。