linux多线程

来源:互联网 发布:百度地图js api 轨迹 编辑:程序博客网 时间:2024/05/04 05:49
/***************************************************
*
*
*
*
***************************************************/


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>


typedef struct 
{
pthread_mutex_t send_lock ;
pthread_mutex_t recv_lock ;
pthread_cond_t cond ;
int data ;
}sig_h ;


int g_quit = 0 ;


void *thread_send1( void *param  )
{
sig_h *phndl = (sig_h*)param ;
int i = 0 ;
while( !g_quit )
{
pthread_mutex_lock( &phndl->send_lock );

phndl->data = i++ ;
printf("send1 thread send %d !\n" , phndl->data );
pthread_cond_signal( &phndl->cond );
pthread_mutex_unlock( &phndl->send_lock );
sleep(1);
}
printf( "thread_send1 quit !\n" );
}


void *thread_send2( void *param )
{
sig_h *phndl = (sig_h*)param ;
int i = 0 ;
while( !g_quit )
{
pthread_mutex_lock( &phndl->send_lock );

phndl->data = i++ ;
printf("send2 thread send %d !\n" , phndl->data );
pthread_cond_signal( &phndl->cond );
                pthread_mutex_unlock( &phndl->send_lock );
sleep(4);
}
printf( "thread_send2 quit !\n" );
}


void *thread_recv( void *param )
{
sig_h *phndl = (sig_h*)param ;


while( !g_quit )
{
pthread_mutex_lock( &phndl->recv_lock );


pthread_cond_wait( &phndl->cond , &phndl->recv_lock );
printf("recv thread recv %d !\n" , phndl->data );
                pthread_mutex_unlock( &phndl->recv_lock );
}
printf( "pthread_recv quit !\n" );
}


void *thread_ctl( void *param )
{
int cnt = 0 ;
while( cnt < 10 )
{
cnt ++ ;
sleep(1);
}
g_quit = 1 ;
printf( "pthread_ctl quit !\n" );
}


int main( int argc , char **argv )
{
sig_h hndl ;
pthread_attr_t attr ;
pthread_condattr_t cattr ;
pthread_mutexattr_t mattr ;
pthread_t t1 , t2 , s1 , tc ;
int status = 0 ;


status |= pthread_mutexattr_init( &mattr );
status |= pthread_condattr_init( &cattr );
status |= pthread_attr_init( &attr );


status |= pthread_mutex_init( &hndl.send_lock , &mattr ) ;
status |= pthread_mutex_init( &hndl.recv_lock , &mattr );
status |= pthread_cond_init( &hndl.cond , &cattr );


status |= pthread_create( &s1 , &attr , thread_recv , (void *)&hndl );
status |= pthread_create( &t1 , &attr , thread_send1 , (void *)&hndl );
status |= pthread_create( &t2 , &attr , thread_send2 , (void *)&hndl );
status |= pthread_create( &tc , &attr , thread_ctl , NULL );


printf( "status %d !\n" , status );
pthread_join( tc , NULL );
pthread_join( t1 , NULL );
pthread_join( t2 , NULL );
//pthread_join( s1 , NULL );


pthread_mutexattr_destroy( &mattr );
pthread_condattr_destroy( &cattr );
pthread_attr_destroy( &attr );


return 0 ;
}
原创粉丝点击