# include<iostream>
# include<thread>
//C++里處理多線程的頭文件是thread
using namespace std;
pthread_mutex_t flock=PTHREAD_MUTEX_INITIALIZER;
//初始化互斥鎖,互斥鎖只能同時被一個對象訪問,如果同時有兩個對訪問纲堵,其中一個會被阻塞
void hello(char c)
{
for(int i=0;i<100;i++) {
pthread_mutex_lock(&flock);//上鎖
cout << c << " " << i << endl;
pthread_mutex_unlock(&flock);//解鎖
}
}
int main()
{
thread t0 (hello,'a');
thread t1 (hello,'b');
t0.join();
t1.join();
//t0.detach();
//t1.detach();
}
(1)當(dāng)使用join()函數(shù)時却嗡,主調(diào)線程(main函數(shù)里有一個主調(diào)線程)阻塞,等待被調(diào)線程終止翻诉,然后主調(diào)線程回收被調(diào)線程資源炮姨,并繼續(xù)運(yùn)行捌刮;上面這段話的意思就是,使用join(),線程運(yùn)行完,main函數(shù)才能結(jié)束舒岸。
(2)當(dāng)使用detach()函數(shù)時绅作,主調(diào)線程繼續(xù)運(yùn)行,被調(diào)線程駐留后臺運(yùn)行蛾派,主調(diào)線程無法再取得該被調(diào)線程的控制權(quán)俄认。當(dāng)主調(diào)線程結(jié)束時,由運(yùn)行時庫負(fù)責(zé)清理與被調(diào)線程相關(guān)的資源碍脏。上面這段話的意思就是梭依,使用detach(),main函數(shù)不用等待線程結(jié)束才能結(jié)束。有時候線程還沒運(yùn)行完典尾,main函數(shù)就已經(jīng)結(jié)束了役拴。