多线程模型相比多进程模型有如下优势:
- 上下文切换时不需要切换数据区和堆,减少了上下文切换的开销
- 可以利用数据区和堆区交换数据
进程:在操作系统构成单独执行流的单位
线程:在进程构成单独执行流的单位
线程的创建和执行流程
#include <pthread.h>
int pthread_create
(
pthread_t* restrict thread, // 保存新创建线程ID的变量地址值
const pthread_attr_t* restrict attr, // 线程属性,若为NULL,则为默认属性
void* (* start_routine)(void *), // 相当于线程main函数的地址值
void* restrict arg //通过第三个参数传递调用函数时包含传递参数信息的变量地址值
);
下面用一个简单的程序演示一下pthread_create的使用方法
// thread1.c
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void* thread_main(void *arg);
int main(int argc, char* argv[])
{
pthread_t t_id;
int thread_param = 5;
if(pthread_create(&t_id, NULL, thread_main, (void*)&thread_param) != 0)
{
puts("pthread_create() error"