2016-03-01 133 views
0

我想寫一個小型的C項目來了解IPC和共享內存中的一些基本機制。我想要做的是讓一個進程增加一個計數器和一個或多個查看此共享變量並執行操作的進程。如果這些過程的代碼存儲在函數中,那將會很好。就像初學者在Linux中的IPC和/或共享內存

int counter = 0 ; 

int timer () { counter ++ } ; 

int proc1 () { /* action 1 */ } ; 

int terminator () { if (counter >= 10) /* terminate processes */} ; 

int main () { 
    counter = 0 ; 
    /* launch timer, proc1, and terminator */ 
    return 0 ; 
} 

有人可以提供一個關於如何做到這一點的例子嗎?也許IPC和共享內存不是正確的技術,我是這個論點的新手。

謝謝!

回答

0

幾天後,我能找到使用這種方法比IPC解決方案,但使用POSIX線程,而不是

#include <pthread.h> 

#define N 10 

int counter = 0 ; 
pthread_mutex_t counter_mutex ; 
pthread_cond_t counter_condition ; 

void * increment (void * arg) { 
    int i = 0 ; 
    sleep (1) ; 
    for (i = 0 ; i < N ; i ++) { 
     pthread_mutex_lock (& counter_mutex) ; 
     counter ++ ; 
     pthread_cond_signal (& counter_condition) ; 
     pthread_mutex_unlock (& counter_mutex) ; 
     sleep (1) ; 
    } 
    pthread_exit ((void *) 0) ; 
} ; 

void * watch (void * arg) { 
    pthread_mutex_lock (& counter_mutex) ; 
    while (counter < N) { 
     pthread_cond_wait (& counter_condition , & counter_mutex) ; 
     printf ("counter = %d\n" , counter) ; 
    } 
    pthread_mutex_unlock (& counter_mutex) ; 
    pthread_exit ((void *) 0) ; 
} ; 

int main () { 

    int i ; 
    pthread_t threads [ 2 ] ; 
    pthread_attr_t attr; 

    pthread_mutex_init (& counter_mutex , (void *) 0) ; 
    pthread_cond_init (& counter_condition , (void *) 0) ; 

    pthread_attr_init (& attr) ; 
    pthread_attr_setdetachstate (& attr , PTHREAD_CREATE_JOINABLE) ; 

    pthread_create (& threads [ 0 ] , & attr , increment , (void *) 0); 
    pthread_create (& threads [ 1 ] , & attr , watch , (void *) 0) ; 

    for (i = 0 ; i < 2 ; i ++) { 
     pthread_join (threads [ i ] , (void *) 0) ; 
    } 

    pthread_attr_destroy (& attr) ; 
    pthread_mutex_destroy (& counter_mutex) ; 
    pthread_cond_destroy (& counter_condition) ; 

    return 0 ; 
} ; 

任何DIS /優勢?