1.基礎線程創建:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void * print_id( void * arg)
//!>這是線程的入口函數
{
printf("TheCurrent process is: %d \n",getpid()); //!>當前進程ID
printf( "TheCurrent 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( "TheMain thread id : %d \n", (unsigned)pthread_self()); //!> 注意輸出的MAIN線程的ID
return0;
}
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) //!> 第二個創建的線程的入口函數
{
printf( "thread 2 id == %d , run now ... \n", ( unsigned )pthread_self());
sleep( 3);