- 论坛徽章:
- 0
|
5可用积分
自己练习写了一个POSIX无名信号量的demo,
创建了两个线程,一个线程对buf实行写操作,
一个线程对buf实行读操作,利用POSIX无名信号量对临界区进行保护,
但是在一个线程进行读操作时,发生信号量死锁.以下是代码:
- #include <errno.h>
- #include <pthread.h>
- #include <semaphore.h>
- #include <signal.h>
- #include <stdio.h>
- #include <string.h>
- #include <unistd.h>
- #define BUF_SIZE 256
- static sem_t g_sem;
- static pthread_once_t g_once = PTHREAD_ONCE_INIT;
- static char g_buf[BUF_SIZE];
- void init_once()
- {
- int err;
- if( -1 == ( err = sem_init( &g_sem, 0, 1 ) ) )
- {
- fprintf( stderr, "sem_init error:%s\n", strerror( err ) );
- return;
- }
- }
- int read_buf( char* a_buf, const size_t a_size )
- {
- int err;
- while( ( -1 == sem_wait( &g_sem ) ) && ( EINTR == errno ) );
- if( EINTR != errno )
- {
- return -1;
- }
- strncpy( a_buf, g_buf, a_size );
-
- return sem_post( &g_sem );
- }
- int write_buf( const char* a_buf, const size_t a_size )
- {
- while( ( -1 == sem_wait( &g_sem ) ) && ( EINTR == errno ) );
- if( EINTR != errno )
- {
- return -1;
- }
- strncpy( g_buf, a_buf, a_size );
-
- return sem_post( &g_sem );
- }
- void* run1( void* arg )
- {
- const char k_data_buf[] = "Nothing is impossible!\n";
- write_buf( k_data_buf, sizeof( k_data_buf ) );
- fprintf( stderr, "Written data ok!\n" );
- return NULL;
- }
- void start_thd1()
- {
- pthread_t thd;
-
- pthread_create( &thd, NULL, run1, NULL );
- pthread_join( thd, NULL );
- }
- void* run2( void* arg )
- {
- char k_data_buf[BUF_SIZE];
- k_data_buf[BUF_SIZE-1] = '\0';
-
-
- fprintf( stderr, "----------run2--------\n" );
- read_buf( k_data_buf, sizeof( k_data_buf ) );
- fprintf( stderr, "%s\n", k_data_buf );
- return NULL;
- }
- void start_thd2()
- {
- pthread_t thd;
-
- pthread_create( &thd, NULL, run2, NULL );
- pthread_join( thd, NULL );
- }
- int main( int argc, char** argv )
- {
- pthread_once( &g_once, init_once );
- start_thd1();
- start_thd2();
-
- return 0;
- }
复制代码
第二个线程调用read_buf时,死在:
while( ( -1 == sem_wait( &g_sem ) ) && ( EINTR == errno ) );
我感觉不是死循环,而是调用sem_wait导致死锁.
程序运行的结果是:
第一个线程的写操作能执行,第二个线程挂了
不知道是什么原因,请高手指教,谢谢!!!!!!!!!!!!! |
最佳答案
查看完整内容
下面的这个条件错误。【 if( EINTR != errno ) { return -1; }】在此条件下,在没有中断的正常情况下,都返回-1了。造成信号量没有释放。
|