TCP IP网络编程:第18章 多线程服务器端的实现

多线程模型相比多进程模型有如下优势:

  1. 上下文切换时不需要切换数据区和堆,减少了上下文切换的开销
  2. 可以利用数据区和堆区交换数据

进程:在操作系统构成单独执行流的单位

线程:在进程构成单独执行流的单位

 

线程的创建和执行流程

#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"
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值