【问题标题】:IPC and/or shared memory in Linux for a beginner面向初学者的 Linux 中的 IPC 和/或共享内存
【发布时间】:2016-06-14 10:24:02
【问题描述】:

我正在尝试编写一个小型 C 项目,只是为了了解 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 和共享内存不是正确的技术,我是这个论点的新手。

谢谢!

【问题讨论】:

    标签: ipc shared-memory


    【解决方案1】:

    几天后我可以找到解决方案,但改用 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 ;
    } ;
    

    使用这种方法比 IPC 有什么缺点/优点吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-08
      • 2011-07-23
      • 1970-01-01
      • 2012-10-31
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      • 2013-01-08
      相关资源
      最近更新 更多