C++多線程與共享指針
一、C++多線程使用
2.1 thread
- <thread> 該頭文件包含有std::thread類與std::this_thread類。以及管理線程的函數。是實現線程的主要文件。
- <atomic> 該頭文件包含有std::atomic和std::atomic_flag類,是實現原子操作的的主要文件。
- <mutex> 包含互斥相關的類與函數。
- <future> 包含有future類及相關的函數。
- <condition_variable> 包含有條件變量的類。
#include<thread>
#include<mutex>
std::thread t(func);
std::thread t(func, parameter)
std::thread t(&class::func, this, parameter)
t.join();
t.detach();
std::thread t3(move(t1));
std::this_thread::sleep_for(chrono::milliseconds(10));
t.get_id();
auto mainThreadId = std::this_thread::get_id();
std::mutex g_lock;
g_lock.lock();
g_lock.unlock();
std::lock_guard<std::mutex> lock(mutex);
std::recursive_mutex mutex;
std::lock_guard<std::recursive_mutex> lock(mutex);
2.2 pthread
#include <pthread.h>
std::pthread_t tids[NUM_THREADS];
std::pthread_create(thread, attr, start_routine, arg);
int ret = pthread_create(&tids[i], NULL, say_hello, NULL);
std::pthread_exit(NULL);
std::pthread_join(threadid, status)
std::pthread_detach(threadid);
std::pthread_attr_t attr;
std::pthread_attr_init(&attr);
std::pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
std::pthread_attr_destroy(&attr);
二、共享指針
- 智能指針是存儲指向動態分配對象指針的類。三種智能指針:
std::shared_ptr/std::unique_ptr/std::weak_ptr.
- 使用時需#include<memory>
2.1 初始化
std::shared_ptr<int> p(new int(1));
std::shared_ptr<int> p2 = p;
std::shared_ptr<int> ptr;
ptr.reset(new int(1));
int *p1 = new int[2];
std::shared_ptr<int> p3(p1);
auto p1 = std::make_shared<int>(10);
auto p2 = std::make_shared<string>(10,"s");
2.2 獲取原始指針
std::shared_ptr<int> ptr(new int(1));
int *p = ptr.get();
2.3指定刪除器
void deleteIntPtr(int* p)
{
delete p;
}
std::shared_ptr<int> p5(new int,deleteIntPtr);
std::shared_ptr<int> p6(new int,[](int* p){delete p;});
std::shared_ptr<int> p6(new int[10],[](int* p){delete[] p;});
std::shared_ptr<int> p7(new int[10],std::default_delete<int[]>);
template<typename T>
std::shared_ptr<T> make_shared_array(size_t size)
{
return std::shared_ptr<T>(new T[size],std::default_delete<T[]>());
}
std::shared_ptr<int> p8 = make_shared_array<int>(10);
std::shared_ptr<char> p9 = make_shared_array<char>(10);
2.4 注意事項
int* p11 = new int;
std::shared_ptr<int> p12(p11);
std::shared_ptr<int> p13(p11);
- 不要在實參中創建shared_ptr,應該先創建一個智能指針,再使用
deleteIntPtr(std::shared_ptr<int>(new int));
std::shared_ptr<int> p14(new int());
deleteIntPtr(p14);
- 要通過shared_from_this()返回this指針
struct A
{
std::shared_ptr<A> getSelf()
{
return std::shared_ptr<A>(this);
}
};
int main()
{
std::shared_ptr<A> sp1(new A);
std::shared_ptr<A> sp2 = sp1->getSelf();
return 0;
}
class A:public std::enable_shared_from_this
{
public:
std::shared_ptr<A> getSelf()
{
return shared_from_this();
}
};
- 免循環使用,如下A/B兩個指針都不會被刪除會有內存泄漏
struct A;
struct B;
struct A
{
std::shared_ptr<B> bptr;
~A(){cout << "A is deleted!"<<endl;}
};
struct B
{
std::shared_ptr<A> aptr;
~B() {cout << "B is deleted!"<<endl;}
};
int main()
{
{
std::shared_ptr<A> ap(new A);
std::shared_ptr<B> bp(new B);
ap->bptr = bp;
bp->aptr = ap;
}
}