POSIX线程库(用户级)
与线程有关的函数构成了一个完整的系列,绝大多数函数的名字以“pthread_”开头
要使用这些函数库,要通过引入头文
链接这些线程函数库时要使用编译器命令的“-lpthread”选项
用户线程和内核线程是1对1的
一、线程创建
- pthread_create函数
头文件:#include<pthread.h>
函数原型:int pthread_create(pthread_t * thread,const pthread_attr_t *attr,void *(*start_routine)(void*),void *arg);
函数功能:创建一个新的线程
返回值:成功返回0,失败返回错误码
参数:
thread:返回线程ID
attr:设置线程的属性,attr为NULL表示使用默认属性
start_routine:是一个函数地址。线程启动后要执行的函数
arg:传给线程启动函数的参数
注:pthread_t 无符号长整型
下面是创建线程代码的具体实现:
#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<pthread.h>
void *thread_run(void *arg)
{
while(1)
{
printf("new pthread,thread is : %u,pid :%d\n",pthread_self(),getpid());
sleep(1);
}
}
int main()
{
pthread_t tid;
pthread_create(&tid,NULL,thread_run,NULL);
while(1)
{
printf("main pthread,thread is : %u,pid %d\n",pthread_self(),getpid());
sleep(3);
}
return 0;
}
按照正常写Makefile的方法写会出现下面的问题