Linux 多线程编程( POSIX )( 一 ) ----> 代码区(2012-01-30 17:07:29)
1.基础线程创建:
#include <stdio.h> #include <stdlib.h> #include <pthread.h>
void * print_id( void * arg ) //!> 这是线程的入口函数 { printf("The Current process is: %d \n", getpid()); //!> 当前进程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 ); //!> 简单的创建线程 if( t_id != 0 ) //!> 注意创建成功返回0 { printf("\nCreate thread error...\n"); exit( EXIT_FAILURE ); } sleep( 1 ); printf("\nThe Current process is: %d \n", getpid()); //!> 当前进程ID printf( "The Main thread id : %d \n", (unsigned)pthread_self() ); //!> 注意输出的MAIN线程的ID return 0; }
2.测试线程的创建和退出
#include <stdio.h> #include <pthread.h> #include <string.h> #include <stdlib.h>
void * entrance_1( void * arg ) //!> 第一个创建的线程的入口函数 { printf( " thread 1 id == %d , run now ... \n", ( unsigned )pthread_self() ); sleep( 3 ); return ( ( void * ) 1 ); }
void * entrance_2( void * arg ) //!> 第二个创建的线程的入口函数 { |