pthread编程(1)

// 2013年01月23日 星期三 13时16分41秒 

// tested libfunc
// -pthread_create @pthred.h
// -pthread_join @pthred.h
// -pthread_self @pthred.h
// -pthread_cancel @pthred.h

// typedef
// -pthread_t : unsigned long int @pthred.h


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

void* threadfn( void *data )
{
	int i;
	for( i = 0; i < 100; i++ )
	{
		// use pthread_self to obtain ID of the calling thread
		printf( "thread-%#lx:	%d...hello,world!\n", (unsigned long)pthread_self(), i );
	}
}

void* threadfn_noreturn( void *data )
{
	long long ll = 0;
	while( 1 )
	{
		// use pthread_self to obtain ID of the calling thread
		printf( "thread-%#lx:	%lld...hello,world!\n", (unsigned long)pthread_self(), ll++ );
	}
}

// NOTE: by default the main thread exits with all other thread terminated.

int main( void )
{
	pthread_t thread;	
	// set attr:pthread_attr_t * to use default attributes and arg:void* to NULL
	if( pthread_create( & thread, NULL, threadfn, NULL ) )
	{	
		//error
		return -1;
	}
	// wait for thread to exit
	// NOTE: the first parameter is not a pointer type
	// set retval: void ** to NULL to ignore the exit status of the target thread
 	pthread_join( thread, NULL );

	// set attr:pthread_attr_t * to use default attributes and arg:void* to NULL
	if( pthread_create( & thread, NULL, threadfn_noreturn, NULL ) )
	{	
		//error
		return -1;
	}
	// now the main thread sleep for a while
	sleep( 1 );
	// now the main thread wakeup to cancel the running thread
	// FIXME: here comes a problem, the last string is printed for twice as listed:
	// thread-0xb75b3b40:	13438...hello,world!thread-0xb75b3b40:	13438...hello,world!

 	pthread_cancel( thread );
	pthread_join( thread, NULL );
	
	return 0;
}



你可能感兴趣的:(linux,pthread,FIXME)