华为机试:多线程

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
#include
#include
#include
#include

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 locker(mtx);
        A.wait(locker);
        res += 'A';
        B.notify_one();
    }
    done = true;
}
void fun_B() {
    while (!done) {
        unique_lock locker(mtx);
        B.wait(locker);
        res += 'B';
        C.notify_one();
    }
}
void fun_C() {
    while (!done) {
        unique_lock locker(mtx);
        C.wait(locker);
        res += 'C';
        D.notify_one();
    }
}
void fun_D() {
    while (!done) {
        unique_lock 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)

 

你可能感兴趣的:(C++开发面试题)