Http://blog.csdn.net/nightfallrove/archive/2008/05/26/2483403.aspx # Include < Iostream >
# Include < Pthread. h >
# Include < String >
# Include < Unistd. h >
Using Namespace STD;
Int Number = 0 ;
Pthread_mutex_t nmutex;
Pthread_cond_t ncond;
Void * Thread1 ( Void * Arg)
... {
Pthread_detach (pthread_self ());
Pthread_mutex_lock ( & Nmutex );
While (Number <= 0 ) // Wait for the main thread to read the number
Pthread_cond_wait ( & Ncond, & Nmutex );
Int Count = Number;
Int Sum = 1 ;
For ( Int I = 1 ; I < Count; I ++ )
Sum + = I;
Cout < " Count by thread1 is " < Sum < Endl;
Pthread_mutex_unlock ( & Nmutex );
Return NULL;
}
Void * Thread2 ( Void * Arg)
... {
Pthread_detach (pthread_self ());
Pthread_mutex_lock ( & Nmutex );
While (Number <= 0 ) // Wait for the main thread to read the number
Pthread_cond_wait ( & Ncond, & Nmutex );
Int Count = Number;
Int Sum = 1 ;
For ( Int I = 1 ; I < Count; I ++ )
Sum + = I;
Cout < " Count by thread2 is " < Sum < Endl;
Pthread_mutex_unlock ( & Nmutex );
Return NULL;
}
Int Main ( Int Argc, Char * Argv [])
... {
Pthread_mutex_init (&Nmutex, null );
Pthread_cond_init (&Ncond, null );
Pthread_t P1, P2;
Pthread_create (&P1, null, thread1, null );
Pthread_create (&P2, null, thread2, null );
// Begin Input
Pthread_mutex_lock (&Nmutex );
Cout< "Input a number
";
CIN
> Number;
Pthread_mutex_unlock (
& Nmutex );
Pthread_cond_signal (
& Ncond );
// End input
Pthread_exit (null );
}