首页 / 操作系统 / Linux / Linux 多线程编程( POSIX )
1.基础线程创建:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void * print_id( void * arg) //!>这是线程的入口函数
{
printf("TheCurrent process is: %d
",getpid()); //!>当前进程ID
printf( "TheCurrent thread id : %d
", (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("
Create thread error...
");
exit(EXIT_FAILURE );
}
sleep( 1);
printf("
The Current process is: %d
",getpid()); //!>当前进程ID
printf( "TheMain thread id : %d
", (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 ...
", ( unsigned )pthread_self());
sleep( 3);
return ( (void * ) 1 );
}
void * entrance_2( void * arg) //!> 第二个创建的线程的入口函数
{
printf( "thread 2 id == %d , run now ...
", ( unsigned )pthread_self());
sleep( 3);
return ( (void * ) 2 );