華爲機試:多線程

https://blog.csdn.net/myblog_dwh/article/details/39522099

題目描述:

問題描述:有4個線程和1個公共的字符數組。線程1的功能就是向數組輸出A,線程2的功能就是向字符輸出B,線程3的功能就是向數組輸出C,線程4的功能就是向數組輸出D。要求按順序向數組賦值ABCDABCDABCD,ABCD的個數由線程函數1的參數指定。[注:C語言選手可使用WINDOWS SDK庫函數]
接口說明:
void init();  //初始化函數
void Release(); //資源釋放函數
unsignedint__stdcall ThreadFun1(PVOID pM)  ; //線程函數1,傳入一個int類型的指針[取值範圍:1 – 250,測試用例保證],用於初始化輸出A次數,資源需要線程釋放
unsignedint__stdcall ThreadFun2(PVOID pM)  ;//線程函數2,無參數傳入
unsignedint__stdcall ThreadFun3(PVOID pM)  ;//線程函數3,無參數傳入
Unsigned int __stdcall ThreadFunc4(PVOID pM);//線程函數4,無參數傳入
char  g_write[1032]; //線程1,2,3,4按順序向該數組賦值。不用考慮數組是否越界,測試用例保證。

代碼:

#include<iostream>
#include<mutex>
#include<condition_variable>
#include<string>
#include<thread>

using namespace std;
string res("");
mutex mtx;
bool done = false;
condition_variable A, B, C, D;
void fun_A(int times) {
    while (times--) {
        unique_lock<mutex> locker(mtx);
        A.wait(locker);
        res += 'A';
        B.notify_one();
    }
    done = true;
}
void fun_B() {
    while (!done) {
        unique_lock<mutex> locker(mtx);
        B.wait(locker);
        res += 'B';
        C.notify_one();
    }
}
void fun_C() {
    while (!done) {
        unique_lock<mutex> locker(mtx);
        C.wait(locker);
        res += 'C';
        D.notify_one();
    }
}
void fun_D() {
    while (!done) {
        unique_lock<mutex> locker(mtx);
        D.wait(locker);
        res += 'D';
        A.notify_one();
    }
}
int main() {
    int num;
    while (cin >> num) {
        res = "";
        thread t1(fun_A, num);
        thread t2(fun_B);
        thread t3(fun_C);
        thread t4(fun_D);
        A.notify_one();
        t1.join();
        t2.join();
        t3.join();
        t4.join();
        cout << res << endl;
        done = false;
    }
    return 0;
}

編譯出錯:

/tmp/a-5c77a2.o: In function `std::thread::thread(void (&)(int), int&)':
a.cpp:(.text._ZNSt6threadC2IRFviEJRiEEEOT_DpOT0_[_ZNSt6threadC2IRFviEJRiEEEOT_DpOT0_]+0x8d): undefined reference to `pthread_create'
/tmp/a-5c77a2.o: In function `std::thread::thread(void (&)())':
a.cpp:(.text._ZNSt6threadC2IRFvvEJEEEOT_DpOT0_[_ZNSt6threadC2IRFvvEJEEEOT_DpOT0_]+0x87): undefined reference to `pthread_create'
clang++: error: linker command failed with exit code 1 (use -v to see invocation)

 

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