c++面試筆記11(使用多線程按照一定的順序輸出ABC)

題目是:使用多線程技術,線程A輸出A,線程B輸出B,線程C輸出C,最後的結果是按順序輸出10個ABC。
代碼爲:
#include< iostream>
#include <sys/types.h>
#include <unistd.h>
#include<pthread.h>
using namespace std;
pthread_mutex_t AB,BC,CA;
void* pth_funA(void* arg)
{
pthread_mutex_lock(&AB);
cout<<“A”;
pthread_mutex_unlock(&BC);
}
void* pth_funB(void* arg)
{
pthread_mutex_lock(&BC);
cout<<“B”;
pthread_mutex_unlock(&CA);
}
void* pth_funC(void* arg)
{
pthread_mutex_lock(&CA);
cout<<“C”;
pthread_mutex_unlock(&AB);
}
int main()
{
pthread_t tidA,tidB,tidC;
for(int i=0;i<10;i++)
{
pthread_create(&tidA,NULL,pth_funA,NULL);
pthread_create(&tidB,NULL,pth_funB,NULL);
pthread_create(&tidC,NULL,pth_funC,NULL);
}
cout<<endl;
pthread_join(tidA,NULL);
pthread_join(tidB,NULL);
pthread_join(tidC,NULL);
return 0;
}
我最開始的寫法沒有使用pthread_mutex_lock,我是在每個pthread_create的後面加一句sleep(1),但是結果並不正確。
下面附一張結果圖:
在這裏插入圖片描述
小結:線程鎖不只是可以鎖全局變量,還可以鎖函數中的某一部分資源或語句。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章