【问题标题】:Increment global variable alternative in 2 threads using pipes in linux在linux中使用管道在2个线程中增加全局变量替代
【发布时间】:2024-05-02 02:05:04
【问题描述】:

我想在两个线程中增加一个全局变量替代项,使用管道进行 sincronization。我该怎么做?

【问题讨论】:

  • 你必须解释你想要做得更好的地方。使用管道同步全局变量的多线程更新就像使用鸡作为螺丝刀一样 - 没有任何意义。
  • 我想知道如何使用管道进行线程间的通信。

标签: c linux multithreading variables pipe


【解决方案1】:

简单示例:

void *pipeReader( void *arg )
{
    int *pipeFDs= ( int * ) arg;
    int readFD = pipeFDs[ 1 ];
    for ( ;; )
    {
        int value;
        read( readFD, &value, sizeof( value ) );
        printf( "value: %d\n", value );
    }
    return( NULL );
}

int main( int argc, char **argv )
{
    int pipeFDs[ 2 ];
    pthread_t tid;
    pipe( pipeFDs );
    pthread_create( &tid, NULL, pipeReader, pipeFDs );
    int ii;
    for ( ii = 1; ii < argc; ii++ )
    {
        int value = atoi( argv[ ii ] );
        write( pipeFDs[ 0 ], &value, sizeof( value ) );
        sleep( 1 );
    }
    return( 0 );
}

我遗漏了正确的头文件,并且该代码没有进行错误检查。

您需要阅读以下内容:

http://man7.org/linux/man-pages/man7/pipe.7.html

【讨论】:

    最近更新 更多