Linux 多线程编程( POSIX )
文章由LinuxBoy分享于2019-03-31 08:03:24
Linux 多线程编程( POSIX )
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);