这里放一些用C++并发写的一些经典算法,有语法不懂的请看上一篇博客或者留言。
github地址:https://github.com/BBuf/C-11-MultiThreads

归并排序

//多线程排序之归并
#include <iostream>
#include <thread>
#include <vector>
#include <fstream>
#include <mutex>
#include <algorithm>
#define NUM_THREADS 5
using namespace std;
mutex mu;
size_t size = 10000000;
const int minSizeOfPerThread = 100000;
static int threadNum = 0;
template <typename T>
vector<T>read_file(string filename){
    ifstream file(filename);
    int now;
    vector <int> data;
    if(file){
        while(file >> now){
            data.push_back(now);
        }
    }
    return data;
}

void my_merge(int arr[], int l, int mid, int r){
    size_t x = 0, y = 0, k = l;
    vector<int> first, second;
    for(size_t i=l; i<mid; i++){
        first.push_back(arr[i]);
    }
    for(size_t i=mid; i<r; i++){
        second.push_back(arr[i]);
    }
    while(x<(mid-l) && y<(r-mid)){
        if(first[x] < second[y]) arr[k++] = first[x++];
        else arr[k++] = second[y++];
    }
    while(x < (mid-l)) arr[k++] = first[x++];
    while(y < (r-mid)) arr[k++] = second[y++];
}

void merge_sort(int l, int r, int arr[]){
    if(l < r){
        int mid  = (l + r) / 2;
        if(mid - l > minSizeOfPerThread){
            thread th1(merge_sort, l, mid, ref(arr));
            thread th2(merge_sort, mid, r, ref(arr));
            th1.join();
            th2.join();
            lock_guard <mutex> lck(mu);
            threadNum += 2;
        }else{
            merge_sort(l, mid, ref(arr));
            merge_sort(mid+1, r, ref(arr));
        }
    }
}

void MergeSort_With_Multithreads(){
    unique_ptr <int[]> testArr0(new int[size]); //可以自己释放内存的智能指针
    for(size_t i = 0; i < size; i++)
        testArr0[i] = rand();
    time_t timeStart = clock();
    merge_sort(0, size, testArr0.get());
    time_t timeEnd = clock();
    cout << "MergeSort Time Is " << (timeEnd - timeStart) << endl;
    cout << "Thread Num is " << threadNum << endl;
}

void Stl_Sort(){
    unique_ptr <int[]> testArr0(new int[size]); //可以自己释放内存的智能指针
    for(size_t i = 0; i < size; i++)
        testArr0[i] = rand();
    time_t timeStart = clock();
    sort(testArr0.get(), testArr0.get()+size-1);
    time_t timeEnd = clock();
    cout << "MergeSort Time Is " << (timeEnd - timeStart) << endl;
}

int main()
{
    MergeSort_With_Multithreads();
    cout << endl;
    Stl_Sort();
    return 0;
}

多线程排序之快速排序

//加速比15358倍
#include <iostream>
#include <algorithm>
#include <thread>
#include <mutex>
using namespace std;

int partition(int arr[], int l, int r){
    swap(arr[l], arr[r]);
    int x = arr[l];
    size_t i = l+1;
    for(size_t j = l+1; j<=r; j++){
        if(arr[j] < x)
            swap(arr[i++], arr[j]);
    }
    swap(arr[l], arr[--i]);
    return i;
}

size_t size = 10000000;
const int minSizeOfPerThread = 100000;
static int threadNum = 0;
mutex mu;

void quick_sort(int arr[], int l, int r){
    if(l < r){
        int mid = partition(arr, l, r);
        if(mid - l > minSizeOfPerThread){
            thread th1(quick_sort , ref(arr), l, mid-1);
            thread th2(quick_sort , ref(arr), mid+1, r);
            th1.join();
            th2.join();
            lock_guard <mutex> lck(mu);
            threadNum += 2;
        }
        else{
            quick_sort(ref(arr), l, mid-1);
            quick_sort(ref(arr), mid+1, r);
        }
    }
}

void Sort_With_multiThreads(){
        unique_ptr <int[]> testArr0(new int[size]); //可以自己释放内存的智能指针
        for(size_t i = 0; i < size; i++)
            testArr0[i] = rand();
        time_t timeStart = clock();
        quick_sort(testArr0.get(), 0, size - 1); //testArr0.get()返回指向被管理对象的指针
        time_t timeEnd = clock();
        cout << "sort time is " << (timeEnd - timeStart) << endl;
        cout << "threadNum Is " << threadNum << endl;
}

void Stl_Sort(){
    unique_ptr <int[]> testArr0(new int[size]); //可以自己释放内存的智能指针
    for(size_t i = 0; i < size; i++)
        testArr0[i] = rand();
    time_t timeStart = clock();
    sort(testArr0.get(), testArr0.get() + size - 1);
    time_t timeEnd = clock();
    cout << "Stl Sort Time is "  << (timeEnd - timeStart) << endl;
}

int main(){
    Sort_With_multiThreads();
    cout << endl;
    Stl_Sort();
    return 0;
}

3个线程连续打印ABC字符串

//c++11 3个线程打印ABC
#include <iostream>
#include <thread>
#include <condition_variable>
#include <vector>
#include <algorithm>

std::mutex mtx;
std::condition_variable tmp;
char c1 = 0;

void work(char ch){
    int cycle = 10;
    char c2 = ch - 'A';
    for(int i=0; i<cycle; i++){
        std::unique_lock <std::mutex> lck(mtx);
        tmp.wait(lck, [c2] {return c2 == c1;});
        std::cout << (char) (c2 + 'A');
        c1 = (c1 + 1) % 3;
        lck.unlock();
        tmp.notify_all();
    }
}

int main(){
    std::vector <std::thread> threads;
    threads.push_back(std::thread(work, 'A'));
    threads.push_back(std::thread(work, 'B'));
    threads.push_back(std::thread(work, 'C'));
    //c++11中加入mem_fn来对成员函数的调用进行相关的封装,不过也需要对方法指针定义为成员函数的形式
    //c++11中利用for_each来遍历一个容器
    std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join));
    std::cout << std::endl;
    getchar();
    return 0;
}

C++11 多线程对矩阵乘法进行加速,加速不明显

//多线程矩阵乘法

#include <thread>
#include <iostream>
#include <vector>
using namespace std;
const int maxn = 2000;
typedef long long LL;

LL A[maxn][maxn], B[maxn][maxn], C[maxn][maxn];

void caculateMat(int row_index, int column_cntA, int colunum_cntB){
    //Go over every column of matrixB
    for(size_t i = 0; i < colunum_cntB; i++){
        //to compute every element of (row_index)-th row of answer
        C[row_index][i] = 0;
        //Calculate answer
        for(size_t j = 0; j < column_cntA; j++){
            C[row_index][i] += A[row_index][j] * B[j][i];
        }
    }
}

int main(){
    for(size_t i = 0; i < maxn; i++){
        for(size_t j = 0; j < maxn; j++){
            A[i][j] = (LL)rand()%10;
        }
    }
    for(size_t i = 0; i < maxn; i++){
        for(size_t j = 0; j < maxn; j++){
            B[i][j] = (LL)rand()%10;
        }
    }
    time_t startTime = clock();
    vector <thread> vt;
    for(int i = 0; i < maxn; i++){
        vt.push_back(thread(caculateMat, i, maxn, maxn));
    }
    for(int i = 0; i < maxn; i++){
        vt[i].join();
    }
    time_t endTime = clock();
    cout << "MultiThreads Mat Multiply time is " << (endTime - startTime) << endl;
    for(int i = 0; i < maxn; i++){
        for(int j = 0; j < maxn; j++){
            C[i][j] = 0;
        }
    }
    startTime = clock();
    for(int i = 0; i < maxn; i++){
        for(int j = 0; j < maxn; j++){
            for(int k = 0; k < maxn; k++){
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }
    endTime = clock();
    cout << "Normal Mat Multiply time is " << (endTime - startTime) << endl;
    return 0;
}