c - 在Linux中使用管道在2个线程中增加全局变量替代方案

标签 c linux multithreading variables pipe

我想使用管道在两个线程中增加全局变量替代方案以进行同步化。我该怎么做?

最佳答案

简单的例子:

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

关于c - 在Linux中使用管道在2个线程中增加全局变量替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29878869/

相关文章:

php - 在不编写扩展的情况下在 PHP 中使用 C/C++ 代码

c - 将一个变量的最低有效字节放入另一个变量

c - 开关盒产生错误输出

c - 仅为 recv 设置超时

java - java中在单独的线程中运行许多方法并等待所有方法完成的最简单方法是什么?

c - POSIX Pthread 两个数字相加 C 代码

java - 如何获取当前TAI时间?

linux - 在 Linux cURL 请求中总是收到 400 错误响应

Unity3D上的Java插件无法启动新线程

Python 队列 block 超时不会超时 - 知道为什么吗?