C++ 線程編程

函數thread

thread* t = new thread(<fun>,<parameter>);

mutex

#include <iostream>
#include <mutex>
#include <thread>
#include <functional>

std::mutex mtx;

void printMultipleChar(int times, char c);

int main(_In_ int argc, _In_reads_(argc) _Pre_z_ char** argv, _In_z_ char** envp) {
    std::cout << "This is showing mutex work in thread" << std::endl;
    std::thread t1(bind(printMultipleChar, std::placeholders::_1, std::placeholders::_2), 50, '$');
    std::thread t2(bind(printMultipleChar, std::placeholders::_1, std::placeholders::_2), 50, '3');
    t1.join();
    t2.join();
    getchar();
    return 0;
}

void printMultipleChar(int times, char c) {
    mtx.lock();
    for (int i = 0; i < times; i++)
    {
        std::cout << c << " ";
    }
    std::cout << std::endl;
    mtx.unlock();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章