线程概念
- 线程是操作系统能够进行调度运算的最小单位,它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。
- 主线程,这是一个进程的初始线程,其入口函数为main函数。
- 新线程的运行时机,一个线程被创建之后有可能不会被马上执行,甚至,在创建它的线程结束后还没被执行;也有可能新线程在当前线程从pthread_create前就已经在运行,甚至,在pthread_create前从当前线程返回前新线程就已经执行完毕。
线程在进程中的内存划分
- 创建一个新的线程,从系统实现的角度看,就是创建了一个新的可调度实体;同一个进程内的线程,共享绝大部分进程的资源,只有少部分信息是线程所特有的,如栈和线程特有数据等。
- 如一进程下4个线程的内存划分图:
![这里写图片描述](https://img-blog.csdn.net/20170529075726572?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdG95aWppdQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
- 可以看到各个线程的stack是独立的,共享heap,bss,数据段和代码段.
一段线程的demo代码
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
void* thread_routine1(void* arg)
{
fprintf(stdout,"thread1:hello world!\n");
sleep(1);
return nullptr;
}
void* thread_routine2(void* arg)
{
fprintf(stdout,"thread2:I am running!\n");
pthread_t main_thread = (pthread_t)arg;
pthread_detach(pthread_self());
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[])
{
pthread_t t1;
if(pthread_create(&t1,NULL,thread_routine1,NULL))
{
fprintf(stdout,"create thread1 fail~\n");
exit(-1);
}
pthread_join(t1, nullptr);
fprintf(stdout,"main thread:thread1 over!\n");
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);
}
- 注意CMakeLists下要添加链接参数 -lpthread
set(CMAKE_CXX_FLAGS “${CMAKE_CXX_FLAGS} -pthread -std=c++11”)
![这里写图片描述](https://img-blog.csdn.net/20170529085713467?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdG95aWppdQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)