线程资源共享
线程间绝大部分资源都是共享的(堆栈共享区)
线程间堆空间是共享的 谁拿着堆空间的入口地址,谁就能访问
共享区也是共享的(cout,printf库都在共享区)
线程间有权限访问/修改其他线程栈数据(用全局变量存储栈变量地址)
线程创建
错误检查
PID, LWP, tid
code:
理解:
线程等待
为什么要有pthread_join
保证了顺序
保证结果可信的(join后线程一定正确处理完)
线程终止
主线程return,表示进程退出,所有线程结束。其他线程return表示只此线程退出
线程中用exit会导致主进程退出
任何地方调用exit,表示整个进程退出
pthread_exit(void*)
只退出调用此函数的线程
pthread_cancel(pthread_t)
取消指定线程
不建议使用pthread_cancel,因为没有进行线程等待,不知到其工作状态。盲目取消正在工作的进程,结果是不可预测的
pthread_cancel后也要pthread_join,不然会遇到类似僵尸问题
joined&detach
线程会有两种被等待状态
默认joined:需要被join
需手动设置:detach;线程分离(主线程不需要等待新线程, 由系统管理回收)
joind&detach作用:
-
pthread_join
:用于阻塞当前线程,等待目标线程执行完毕并回收其资源。 -
pthread_detach
:将线程与当前线程分离,线程执行完毕后自动回收资源,避免阻塞。
- 一旦线程被分离,它就不能再通过
pthread_join
来等待其结束 - 调用
pthread_detach
后,线程的资源会在其执行完毕后自动释放(由系统回收),不需要显式地调用pthread_join
- 如果没有使用
pthread_join
,但又不调用pthread_detach
,则会导致线程资源无法释放,造成资源泄漏。
为什么线程不提供非阻塞等待(没有pthread_tryjoin接口)
- 防止cpu频繁轮询浪费资源
- 非阻塞等待可能导致资源不正确回收
- 可用detach直接分离线程来替代非阻塞等待
阻塞等待&非阻塞等待
-
阻塞等待:等待某个条件满足(如线程结束)时,线程被挂起,不做其他操作。
-
非阻塞等待:不会等待,检查条件是否满足,若不满足则立即返回,线程不被挂起。
code
mythread.cc
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <thread>// 线程的局部存储
// __thread只能修饰内置类型
__thread int shared_value = 100;std::string toHex(pthread_t tid)
{// 4. 进程内的函数,线程共享char buffer[64];snprintf(buffer, sizeof(buffer), "0x%lx", tid);return buffer;
}void *start(void *args)
{std::string name = static_cast<const char *>(args);sleep(1);while (true){printf("I am a new thread, name: %s, shared_value: %d, &shared_value: %p\n", name.c_str(), shared_value, &shared_value);sleep(1);}return nullptr;
}int main()
{pthread_attr_t attr;pthread_t tid;pthread_create(&tid, nullptr, start, (void *)"thread-1");std::cout << "I am a new thread, name: main, " << toHex(pthread_self())<< ", NEW thread id: " << toHex(tid) << std::endl;while (true){printf("main thread, shared_value: %d, &shared_value: %p\n", shared_value, &shared_value);shared_value += 10;sleep(1);}pthread_join(tid, nullptr);return 0;
}// int *addr = nullptr;// void *start1(void *args)
// {
// std::string name = static_cast<const char *>(args);
// int a = 100;
// while (true)
// {
// std::cout << name << " local val a: " << a << std::endl;
// sleep(1);
// }
// }// void *start(void *args)
// {
// // 可以的!
// // pid_t id = fork();
// // if(id == 0)
// // {
// // // ....
// // }
// // pthread_detach(pthread_self());
// // std::string name = static_cast<const char *>(args);
// // while (true)
// // {
// // // if(addr != nullptr)
// // //std::cout << name << " mod val a: " << (*addr)++ << std::endl;
// // std::cout << "I am a new thread" << std::endl;
// // sleep(1);
// // // break;
// // }
// // return 0; // 9. 新线程return表示该线程退出
// // exit(1); // 任何地方调用exit,表示进程退出!
// // pthread_exit((void*)10);
// }// int main()
// {
// // // pthread_t tid1, tid2;
// // pthread_t tid;
// // pthread_create(&tid, nullptr, start, (void *)"thread-1");
// // // pthread_detach(tid);
// // sleep(5);// // // int n = pthread_cancel(tid);
// // // std::cout << "取消线程: " << tid << std::endl;// // // sleep(5);// // void *ret = nullptr;
// // int n = pthread_join(tid, &ret); //PTHREAD_CANCELED;
// // std::cout << "new thread exit code: " << (long long int)ret << " ,n: " << n << std::endl;// // // pthread_create(&tid1, nullptr, start2, (void *)"thread-1");
// // // pthread_join(tid1, nullptr);
// // return 0; // 9. 主线程return,表示进程结束!
// }// class ThreadData
// {
// public:
// ThreadData()
// {}
// void Init(const std::string &name, int a, int b)
// {
// _name = name;
// _a = a;
// _b = b;
// }
// void Excute()
// {
// _result = _a + _b;
// }
// int Result(){ return _result; }
// std::string Name(){ return _name; }
// void SetId(pthread_t tid) { _tid = tid;}
// pthread_t Id() { return _tid; }
// int A(){return _a;}
// int B(){return _b;}
// ~ThreadData()
// {}
// private:
// std::string _name;
// int _a;
// int _b;
// int _result;
// pthread_t _tid;
// };// // class outData
// // {// // };// // 5. 全局变量在线程内部是共享的
// int gval = 100;
// // std::queue<int> q;
// // char buffer[4096];// std::string toHex(pthread_t tid)
// {
// // 4. 进程内的函数,线程共享
// char buffer[64];
// snprintf(buffer, sizeof(buffer), "0x%lx", tid);
// return buffer;
// }// void *routine2(void *args)
// {
// std::string name = static_cast<const char *>(args);
// while (true)
// {
// // 3. 不加保护的情况下,显示器文件就是共享资源!
// std::cout << "我是新线程,我的名字是: " << name << ", my tid is : " << toHex(pthread_self()) << ", 全局变量(只是检测):" << gval << std::endl;
// sleep(1);
// // 6. 线程一旦出现异常,可能会导致其他线程全部崩溃
// // 6.1 信号
// int *p = nullptr;
// *p = 100;
// }
// return 0;
// }// // 被重入了!!
// void *routine(void *args)
// {
// //std::string name = static_cast<const char *>(args);
// ThreadData *td = static_cast<ThreadData *>(args);
// while (true)
// {
// // 3. 不加保护的情况下,显示器文件就是共享资源!
// std::cout << "我是新线程,我的名字是: " << td->Name() << ", my tid is : " << toHex(pthread_self()) << ", 全局变量(会修改):" << gval << std::endl;
// gval++;
// td->Excute();
// sleep(1);
// break;
// }
// // 8.返回值问题: 返回参数,可以是变量,数字,对象!
// // 8.1: 理论上,堆空间也是共享的!谁拿着堆空间的入口地址,谁就能访问该堆区!
// // int *p = new int(10);
// // return (void*)p; // 线程退出方式1:线程入口函数return,表示线程退出// return td;
// }// #define NUM 10// int main()
// {// // ThreadData td[NUM];
// // // 准备我们要加工处理的数据
// // for(int i = 0; i < NUM; i++)
// // {
// // char id[64];
// // snprintf(id, sizeof(id), "thread-%d", i);
// // td[i].Init(id, i*10, i*20);
// // }// // // 创建多线程
// // for(int i = 0; i < NUM; i++)
// // {
// // pthread_t id;
// // pthread_create(&id, nullptr, routine, &td[i]);
// // td[i].SetId(id);
// // }// // // 等待多个线程
// // for(int i =0; i< NUM;i++)
// // {
// // pthread_join(td[i].Id(), nullptr);
// // }// // // 汇总处理结果
// // for(int i =0;i < NUM; i++)
// // {
// // printf("td[%d]: %d+%d=%d[%ld]\n", i, td[i].A(), td[i].B(), td[i].Result(), td[i].Id());
// // }
// // 1. 新线程和main线程谁先运行,不确定
// // 2. 线程创建出来,要对进程的时间片进行瓜分
// // 8. 传参问题: 传递参数,可以是变量,数字,对象!
// // pthread_t tid1;
// // ThreadData *td = new ThreadData("thread-1", 10, 20);
// // pthread_create(&tid1, nullptr, routine1, td);// // // 7. 线程创建之后,也是要被等待和回收的!
// // // 7.1 理由:a. 类似僵尸进程的问题 b. 为了知道新线程的执行结果
// // ThreadData *rtd = nullptr;
// // int n = pthread_join(tid1, (void**)&rtd); // 我们可以保证,执行完毕,任务一定处理完了,结果变量一定已经被写入了!
// // if(n != 0)
// // {
// // std::cerr << "join error: " << n << ", " << strerror(n) << std::endl;
// // return 1;
// // }
// // std::cout << "join success!, ret: " << rtd->Result() << std::endl;
// // delete td;// // pthread_t tid2;
// // pthread_create(&tid2, nullptr, routine2, (void *)"thread-2");// // pthread_t tid3;
// // pthread_create(&tid3, nullptr, routine, (void *)"thread-3");// // pthread_t tid4;
// // pthread_create(&tid4, nullptr, routine, (void *)"thread-4");// // std::cout << "new thread id: " << tid << std::endl;
// // printf("new thread id: 0x%lx\n", tid1);
// // printf("new thread id: 0x%lx\n", tid2);
// // printf("new thread id: 0x%lx\n", tid3);
// // printf("new thread id: 0x%lx\n", tid4);// // while (true)
// // {
// // std::cout << "我是main线程..." << std::endl;
// // sleep(1);
// // }
// }// // void *routine(void *args)
// // {
// // std::string name = static_cast<const char *>(args);
// // while (true)
// // {
// // std::cout << "我是新线程,我的名字是: " << name << std::endl;
// // sleep(1);
// // }
// // return 0;
// // }// // int main()
// // {
// // std::thread t([](){
// // while (true)
// // {
// // std::cout << "我是新线程,我的名字是 : new thread " << std::endl;
// // sleep(1);
// // }
// // });// // while (true)
// // {
// // std::cout << "我是main线程..." << std::endl;
// // sleep(1);
// // }// // // pthread_t tid;
// // // int n = pthread_create(&tid, nullptr, routine, (void *)"thread-1");
// // // if (n != 0)
// // // {
// // // std::cout << "create thread error: " << strerror(n) << std::endl;
// // // return 1;
// // // }
// // // while (true)
// // // {
// // // std::cout << "我是main线程..." << std::endl;
// // // sleep(1);
// // // }
// // }
main.cc
#include "Thread.hpp"
#include <unordered_map>
#include <memory>#define NUM 10// using thread_ptr_t = std::shared_ptr<ThreadModule::Thread>;class threadData
{
public:int max;int start;
};void Count(threadData td)
{for (int i = td.start; i < td.max; i++){std::cout << "i == " << i << std::endl;sleep(1);}
}int main()
{threadData td;td.max = 60;td.start = 50;ThreadModule::Thread<threadData> t(Count, td);// ThreadModule::Thread<int> t(Count, 10);t.Start();t.Join();// 先描述,在组织!// std::unordered_map<std::string, thread_ptr_t> threads;// // 如果我要创建多线程呢???// for (int i = 0; i < NUM; i++)// {// thread_ptr_t t = std::make_shared<ThreadModule::Thread>([](){// while(true)// {// std::cout << "hello world" << std::endl;// sleep(1);// }// });// threads[t->Name()] = t;// }// for(auto &thread:threads)// {// thread.second->Start();// }// for(auto &thread:threads)// {// thread.second->Join();// }// ThreadModule::Thread t([](){// while(true)// {// std::cout << "hello world" << std::endl;// sleep(1);// }// });// t.Start();// std::cout << t.Name() << "is running" << std::endl;// sleep(5);// t.Stop();// std::cout << "Stop thread : " << t.Name()<< std::endl;// sleep(1);// t.Join();// std::cout << "Join thread : " << t.Name()<< std::endl;return 0;
}
Thread.hpp
#ifndef _THREAD_HPP__
#define _THREAD_HPP__#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>
#include <sys/types.h>
#include <unistd.h>// v2
namespace ThreadModule
{static int number = 1;enum class TSTATUS{NEW,RUNNING,STOP};template <typename T>class Thread{using func_t = std::function<void(T)>;private:// 成员方法!static void *Routine(void *args){Thread<T> *t = static_cast<Thread<T> *>(args);t->_status = TSTATUS::RUNNING;t->_func(t->_data);return nullptr;}void EnableDetach() { _joinable = false; }public:Thread(func_t func, T data) : _func(func), _data(data), _status(TSTATUS::NEW), _joinable(true){_name = "Thread-" + std::to_string(number++);_pid = getpid();}bool Start(){if (_status != TSTATUS::RUNNING){int n = ::pthread_create(&_tid, nullptr, Routine, this); // TODOif (n != 0)return false;return true;}return false;}bool Stop(){if (_status == TSTATUS::RUNNING){int n = ::pthread_cancel(_tid);if (n != 0)return false;_status = TSTATUS::STOP;return true;}return false;}bool Join(){if (_joinable){int n = ::pthread_join(_tid, nullptr);if (n != 0)return false;_status = TSTATUS::STOP;return true;}return false;}void Detach(){EnableDetach();pthread_detach(_tid);}bool IsJoinable() { return _joinable; }std::string Name() { return _name; }~Thread(){}private:std::string _name;pthread_t _tid;pid_t _pid;bool _joinable; // 是否是分离的,默认不是func_t _func;TSTATUS _status;T _data;};
}// v1
// namespace ThreadModule
// {
// using func_t = std::function<void()>;
// static int number = 1;
// enum class TSTATUS
// {
// NEW,
// RUNNING,
// STOP
// };// class Thread
// {
// private:
// // 成员方法!
// static void *Routine(void *args)
// {
// Thread *t = static_cast<Thread *>(args);
// t->_status = TSTATUS::RUNNING;
// t->_func();
// return nullptr;
// }
// void EnableDetach() { _joinable = false; }// public:
// Thread(func_t func) : _func(func), _status(TSTATUS::NEW), _joinable(true)
// {
// _name = "Thread-" + std::to_string(number++);
// _pid = getpid();
// }
// bool Start()
// {
// if (_status != TSTATUS::RUNNING)
// {
// int n = ::pthread_create(&_tid, nullptr, Routine, this); // TODO
// if (n != 0)
// return false;
// return true;
// }
// return false;
// }
// bool Stop()
// {
// if (_status == TSTATUS::RUNNING)
// {
// int n = ::pthread_cancel(_tid);
// if (n != 0)
// return false;
// _status = TSTATUS::STOP;
// return true;
// }
// return false;
// }
// bool Join()
// {
// if (_joinable)
// {
// int n = ::pthread_join(_tid, nullptr);
// if (n != 0)
// return false;
// _status = TSTATUS::STOP;
// return true;
// }
// return false;
// }
// void Detach()
// {
// EnableDetach();
// pthread_detach(_tid);
// }
// bool IsJoinable() { return _joinable; }
// std::string Name() {return _name;}
// ~Thread()
// {
// }// private:
// std::string _name;
// pthread_t _tid;
// pid_t _pid;
// bool _joinable; // 是否是分离的,默认不是
// func_t _func;
// TSTATUS _status;
// };
// }#endif