linux线程1

线程概念

  • 线程是操作系统能够进行调度运算的最小单位,它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。
  • 主线程,这是一个进程的初始线程,其入口函数为main函数。
  • 新线程的运行时机,一个线程被创建之后有可能不会被马上执行,甚至,在创建它的线程结束后还没被执行;也有可能新线程在当前线程从pthread_create前就已经在运行,甚至,在pthread_create前从当前线程返回前新线程就已经执行完毕。

线程在进程中的内存划分

  • 创建一个新的线程,从系统实现的角度看,就是创建了一个新的可调度实体;同一个进程内的线程,共享绝大部分进程的资源,只有少部分信息是线程所特有的,如栈和线程特有数据等。
  • 如一进程下4个线程的内存划分图:
    这里写图片描述
  • 可以看到各个线程的stack是独立的,共享heap,bss,数据段和代码段.

一段线程的demo代码

#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>

/*线程1入口函数*/
void* thread_routine1(void* arg)
{
    fprintf(stdout,"thread1:hello world!\n");
    sleep(1);
    //线程1退出
    return nullptr;
}

/*线程2入口函数*/
void* thread_routine2(void* arg)
{
    fprintf(stdout,"thread2:I am running!\n");
    pthread_t main_thread = (pthread_t)arg;
    //此线程分离,不能再被连接
    pthread_detach(pthread_self());

    //判断主线程id和此线程id是否相同
    if(!pthread_equal(main_thread,pthread_self()))
    {
        fprintf(stdout,"main thread is not equal to thread 2!\n");
    }

    //等待主线程终止
    pthread_join(main_thread, nullptr);
    fprintf(stdout,"thread2:main thread exit~\n");
    fprintf(stdout,"thread2:exit~\n");
    fprintf(stdout,"thread2:process exit~\n");

    //此线程终止
    pthread_exit(nullptr);
}

int main(int argc,char* argv[])
{
    //创建线程1
    pthread_t t1;
    if(pthread_create(&t1,NULL,thread_routine1,NULL))
    {
        fprintf(stdout,"create thread1 fail~\n");
        exit(-1);
    }

    //等待线程1终止
    pthread_join(t1, nullptr);
    fprintf(stdout,"main thread:thread1 over!\n");

    //创建线程2
    pthread_t t2;
    if(pthread_create(&t2,NULL,thread_routine2,(void*)pthread_self()))
    {
        fprintf(stdout,"create thread2 fail~\n");
        exit(-1);
    }

    fprintf(stdout,"main thread:sleeping...\n");
    sleep(3);
    //主线程终止
    fprintf(stdout,"main thread exit~\n");
    pthread_exit(nullptr);
    //return 0;
}
  • 注意CMakeLists下要添加链接参数 -lpthread
    set(CMAKE_CXX_FLAGS “${CMAKE_CXX_FLAGS} -pthread -std=c++11”)
    这里写图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值