目录
什么是线程
深入理解页表
理解进程和线程
实践线程操作
#include<iostream>
#include<unistd.h>
#include<pthread.h>
#include<cstring>
#include<cstdlib>
#include<cstdio>
using namespace std;
void* start_routine(void * arg)
{
while(true){
printf("%s\n", (char*)arg);
sleep(1);
}
}
int main()
{
pthread_t thread_id;
char buff[64];
snprintf(buff, sizeof(buff), "我是新创建的线程,我正在运行");
pthread_create(&thread_id, nullptr, start_routine, (void*)buff);
int counter = 10;
while(counter--){
printf("我是主线程,运行倒计时:%d\n", counter);
sleep(1);
}
return 0;
}
#include<iostream>
#include<unistd.h>
#include<pthread.h>
#include<cstring>
#include<cstdlib>
using namespace std;
#define MAX 10
void* _start_test(void* arg){
while(true){
sleep(1);
cout << (char*)arg << endl;
}
return nullptr;
}
int main(){
for (int i = 0; i<MAX; i++){
pthread_t tid;
char buff[64];
snprintf(buff, sizeof(buff), "this is %d thread", i);
pthread_create(&tid, nullptr, _start_test, buff);
}
while(true){
sleep(1);
cout << "我是主线程"<<endl;
}
return 0;
}
线程终止
线程等待
分离线程
线程取消
TCB
线程的优缺点
优点
缺点
C++提供的线程库
#include<thread>
#include<iostream>
#include<unistd.h>
using namespace std;
void* start_routine()
{
int counter = 10;
while(counter--){
sleep(1);
cout << "我是新创建的线程,运行倒计时:" << counter <<endl;
}
return nullptr;
}
int main()
{
//创建一个线程,并把执行函数传递过去
thread t1(start_routine);
cout << "我是主线程" <<endl;
//主线程阻塞等待回收子线程
t1.join();
cout << "线程回收完毕,准备退出"<<endl;
return 0;
}