我想使用管道在两个线程中增加全局变量替代方案以进行同步化。我该怎么做?
最佳答案
简单的例子:
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 );
}
我遗漏了正确的头文件,并且该代码不进行错误检查。
您需要阅读以下内容:
关于c - 在Linux中使用管道在2个线程中增加全局变量替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29878869/