Linux 多線程編程( POSIX )( 一 ) ----> 代碼區(qū)(2012-01-30 17:07:29)
1.基礎(chǔ)線程創(chuàng)建:
#include <stdio.h> #include <stdlib.h> #include <pthread.h>
void * print_id( void * arg ) //!> 這是線程的入口函數(shù) { printf("The Current process is: %d \n", getpid()); //!> 當(dāng)前進(jìn)程ID printf( "The Current thread id : %d \n", (unsigned)pthread_self() ); //!> 注意此處輸出的子線程的ID }
int main( ) { pthread_t t; int t_id; t_id = pthread_create( &t, NULL, print_id, NULL ); //!> 簡(jiǎn)單的創(chuàng)建線程 if( t_id != 0 ) //!> 注意創(chuàng)建成功返回0 { printf("\nCreate thread error...\n"); exit( EXIT_FAILURE ); } sleep( 1 ); printf("\nThe Current process is: %d \n", getpid()); //!> 當(dāng)前進(jìn)程ID printf( "The Main thread id : %d \n", (unsigned)pthread_self() ); //!> 注意輸出的MAIN線程的ID return 0; }
2.測(cè)試線程的創(chuàng)建和退出
#include <stdio.h> #include <pthread.h> #include <string.h> #include <stdlib.h>
void * entrance_1( void * arg ) //!> 第一個(gè)創(chuàng)建的線程的入口函數(shù) { printf( " thread 1 id == %d , run now ... \n", ( unsigned )pthread_self() ); sleep( 3 ); return ( ( void * ) 1 ); }
void * entrance_2( void * arg ) //!> 第二個(gè)創(chuàng)建的線程的入口函數(shù) { |