gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:10:21 25 4
gpt4 key购买 nike

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

最佳答案

简单的例子:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com