Linux多线程程编已经有成熟的 pthread库进行支持,首先对多线程程编的常用API进行梳理。
线程
并发性和并行性
在单个处理器的多线程进程中,处理器可以在线程之间切换执行资源,从而执行并发
在共享内存的多处理器的多线程进程中,进程中的每一个线程都可以在一个单独的cpu上并发执行。
用户级线程
线程仅在进程内部是可见的,进程内部的线程会共享诸如地址空间、打开的文件等所有进程资源
以下状态对每一个线程来说是唯一的
- 线程ID
- 寄存器状态
- 栈
- 信号掩码
- 优先级
线程专用储存
常用API
线程主要关注的点有三个,线程的创建,线程的退出以及线程等待 ,在linux下需要引用头文件
#include <pthread.h>
创建线程
int pthread_create(pthread_t *tidp,const pthread_attr_t *attr, (void*)(*start_rtn)(void*),void *arg);
编译链接选项
-lpthread,由于pthread库不是Linux系统的默认库,而是POSIX的线程库,因此在编译的时候需要加上-lpthread或者-pthread来显示链接该库,函数在执行错误的时候并不会修改系统错误信息errno而是返回错误值。
入参解析
1.pthread_t tidp 线程ID的指针,对于每一个线程来说是唯一的
2.pthread_attr_t attr 此参数为Posix的线程属性,缺省值为NULL
3.(void)(start_rtn)(void*) 线程运行函数的起始地址
4.运行函数的参数,多个参数的时候可以定义结构体
返回值解析
如果创建线程成功,返回0;创建线程失败返回错误的原因;
如果线程创建成功,tidp指向的内存单元被设置为新创建的线程的线程ID
代码示例
1 #include<stdio.h> 2 #include<pthread.h> 3 #include<string.h> 4 #include<sys/types.h> 5 #include<unistd.h> 6 void* printP(void* arg) 7 { 8 int i=0; 9 10 while (i != 100) 11 { 12 i++; 13 printf("This is the %d times print\n", i); 14 sleep(1); 15 16 } 17 18 } 19 20 bool CreateThread() 21 { 22 pthread_t m_pthread; 23 printf("This is new pthread\n"); 24 25 //创建线程 26 if (pthread_create(&m_pthread, NULL, printP, NULL) != 0) 27 { 28 return false; 29 } 30 return true; 31 32 } 33 34 int main() 35 { 36 if(CreateThread() == false) 37 { 38 return -1; 39 } 40 41 int i = 0; 42 while(i < 100) 43 { 44 i++; 45 printf("This is the %d times say Hello!\n",i); 46 sleep(1); 47 } 48 return 1; 49 }
代码运行结果
[jager@VM_0_10_centos pthread]$ ./test This is new pthread This is the 1 times say Hello! This is the 1 times print This is the 2 times say Hello! This is the 2 times print This is the 3 times say Hello! This is the 3 times print This is the 4 times say Hello! This is the 4 times print This is the 5 times say Hello! This is the 5 times print This is the 6 times say Hello!
注意
1.线程创建之后,主线程main与pthread线程会交替执行。
来源:https://www.cnblogs.com/limushu/p/11447164.html