线程的使用(与进程对比记忆)
pthread_self():获取线程ID / getpid():获取进程ID
pthread_create:创建线程 / fork(): 创建进程
(注意:其中线程执行函数是,函数地址的指针)
***int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);***
参数一:pthread_t 类型地址
参数二:线程属性
参数三:线程函数地址
参数四:线程函数的形参
单个线程的创建
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
void *pthread_func(void * arg)
{
printf("IN thread: tid = %ld, pid=%d\n",pthread_self(),getpid());
}
int main()
{
pthread_t tid;
int ret = pthread_create( &tid , NULL , pthread_func,NULL);
if(ret != 0)
{
printf("pthread_creat error\n");//perror打印的是系统调用,strerror(int mun)是库函数
exit(1);
}
printf("IN main pthread: tid = %ld , pid =%d\n",pthread_self(),getpid());
sleep(1);
return 0 ;
}
多个线程的创建
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
void *pthread_func(void * arg)
{
int i = (int)arg;
sleep(i);
printf("%dth IN thread: tid = %lu, pid=%u\n",i+1,pthread_self(),getpid());
return NULL;
}
int main()
{
pthread_t tid;
int i =0,ret;
for(i =0; i< 5 ; ++i)
{
ret = pthread_create( &tid , NULL , pthread_func,(void *)i);//此处i用值传递,用&i传递会出错
if(ret != 0)
{
printf("pthread_creat error");
exit(1);
}
}
sleep(i);
return 0 ;
}