动机

多线程的优点
多线程的定义
多核编程
在多处理器系统中,多核编程机制让应用程序可以更有效地将自身的多个执行任务(并发的线程)分散到不同的处理器上运行,以实现并行计算。

多线程模型

三种多线程模型

线程库
PTHREADS
Pthreads是POSIX标准定义的线程创建与同步API。
不同的操作系统对该标准的实现不尽相同。
本节实验所用的API是Linux对Pthreads的实现
#include
#include
#include
#include
void* threadFunc(void* arg){ //线程函数
// sleep(3);
printf("In NEW thread\n");
}
int main()
{
pthread_t tid;
//线程创建函数
/*参数列表
1. Thread id address
2. Thread attributes address
3. Thread function address
4. Thread parameters address
*/
pthread_create(&tid, NULL, threadFunc, NULL);
//等待指定的线程结束
//pthread_join(tid, NULL);
printf("In main thread\n");
return 0;
}
有一个疑惑的地方,如果这句 pthread_join(tid, NULL); 放在 printf(“In main thread\n”); 后面就可以等待三秒执行,如果放在前面,则程序会先退出。
编译该段代码时,请注意gcc要加入新的参数,命令如下:
gcc helloThread.c -o helloThread -l pthread
gcc helloThread.c -o helloThread pthread (常用)